目录:
- 一、组件的选项watch和实例方法$watch不再支持点分隔符的字符串路径
- 二、新增
watchEffect,俗称函数副作用
一、组件的选项watch和实例方法$watch不再支持点分隔符的字符串路径。
- 以
.分割的表达式不再被watch和$watch支持,可以使用一个计算函数作为watch和$watch的参数实现。
来看一个事例
比如我们现在想用watch监听data中,counter的变化,那么给watch传值的时候,this.state.foo.counter这样的路径就不可避免,接下来我们看看vue2.0和vue3.0的区别在哪
export default{
data(){
return{
state:{
foo:{
counter:23
}
}
}
}
}
共同点
- vue2.0和vue3.0都可以使用函数返回要监听的值
-
如果项目中使用了ts,那么watch就会自动检测出异常
image.png
在3.0中
<template>
<h1>Watch新特性测试</h1>
<p>
counter:{{ state.foo.counter }} <button @click="handleClick">+1</button>
</p>
<p>counter改变了{{ state.changeCounter }}次</p>
</template>
<script lang='ts'>
import { defineComponent, reactive, watch } from "vue";
export default defineComponent({
data() {
return {
state: {
foo: {
counter: 23,
},
changeCounter: 0,
},
};
},
mounted() {
this.$watch(
() => this.state.foo.counter,
(newVal: string) => {
if (newVal) {
this.state.changeCounter++;
}
}
);
},
methods: {
handleClick() {
this.state.foo.counter++;
},
},
});
</script>
<style scoped>
</style>
在vue2.0中watch的使用跟vue3.0中的一样
<template>
<div>
<h1>watch测试</h1>
<p>counter:{{ state.foo.counter }}</p>
<button @click="handleClick">增加</button>
</div>
</template>
<script>
export default {
data() {
return {
state: {
foo: {
counter: 0,
},
},
};
},
mounted() {
this.$watch(
() => this.state.foo.counter,
(newVal) => {
if (newVal) {
console.log("counter改变");
}
}
);
},
methods: {
handleClick() {
this.state.foo.counter++;
},
},
};
</script>
不同点
- 如果换成字符串的形式,vue2.0还会支持,vue3.0就不再支持了
3.0不再支持这种写法、2.0依旧支持,自己可以下去试一下。
mounted() {
this.$watch("state.foo.counter", (newVal) => {
if (newVal) {
console.log("counter改变");
}
});
},
二、watchEffect
- 使用场景:某个属性改变的时候,我们需要做一些事情,这种情况下我们需要用
watchEffect
我们用上面的那个vue3.0的例子做实验,用一下这个watchEffect
<template>
<h1>Watch新特性测试</h1>
<p>
counter:{{ state.foo.counter }} <button @click="handleClick">+1</button>
</p>
<p>counter改变了{{ state.changeCounter }}次</p>
</template>
<script lang='ts'>
import { defineComponent, reactive, watch, watchEffect } from "vue";
export default defineComponent({
data() {
return {
state: {
foo: {
counter: 23,
},
changeCounter: 0,
},
};
},
mounted() {
this.$watch(
() => this.state.foo.counter,
(newVal: string) => {
if (newVal) {
this.state.changeCounter++;
}
}
);
watchEffect(() => {
console.log("函数副作用", this.state.foo.counter);
});
},
methods: {
handleClick() {
this.state.foo.counter++;
},
},
});
</script>
