06. 监听数据
于2022-10-10 17:31:38发布
101
使用watc函数,可以监听数据或者对象中的数据变化。当数据发生改变时,则会被捕获到。
监听基本数据类型
<template>
<div>
{{ name }}
<button @click="setName">修改name</button>
</div>
</template>
<script>
export default {
data() {
return {
name: "tom",
};
},
methods: {
setName() {
this.name = "marry";
},
},
watch: {
name(newV, oldV) {
console.log(`name被改变了,新的值是${newV}---旧的值是${oldV}`);
},
},
};
</script>
监听对象中的某个数据
<template>
<div>
<p>
{{ queryInfo.type }}
<button @click="setType">修改type</button>
</p>
</div>
</template>
<script>
export default {
data() {
return {
queryInfo: {
type: 1,
},
};
},
methods: {
setType() {
this.queryInfo.type = 2;
},
},
watch: {
"queryInfo.type": {
handler: (newV, oldV) => {
console.log(`type被改变了,新的值是${newV}---旧的值是${oldV}`);
},
},
},
};
</script>
监听整个对象
监听对象是否发生变化,则需要在watch函数中传入 deep : true,代表深度监听。(上面的2个例子称为浅度监听)
<template>
<div>
<p>
{{ queryInfo.type }}
<button @click="setType">修改type</button>
</p>
</div>
</template>
<script>
export default {
data() {
return {
queryInfo: {
type: 1,
},
};
},
methods: {
setType() {
this.queryInfo.type = 2;
},
},
watch: {
"queryInfo": {
deep: true,
handler: (newV, oldV) => {
console.log(`type被改变了,新的值是${JSON.stringify(newV)}---旧的值是${JSON.stringify(oldV)}`);
},
},
},
};
</script>
运行上面的例子会发现,newV 和 oldV的值是一样的,原因是
解决方法是用计算属性,如下 :
<template>
<div>
<p>
{{ queryInfo.type }}
<button @click="setType">修改type</button>
</p>
</div>
</template>
<script>
export default {
computed: {
queryInfoNew() {
return JSON.parse(JSON.stringify(this.queryInfo))
}
},
data() {
return {
queryInfo: {
type: 1,
},
};
},
methods: {
setType() {
this.queryInfo.type = 2;
},
},
watch: {
"queryInfoNew": {
deep: true,
handler: (newV, oldV) => {
console.log(`type被改变了,新的值是${JSON.stringify(newV)}---旧的值是${JSON.stringify(oldV)}`);
},
},
},
};
</script>
immediate
有时候想让watch在一开始,自动执行一次。可以添加immediate属性。
<template>
<div>
{{ name }}
<button @click="setName">修改name</button>
</div>
</template>
<script>
export default {
data() {
return {
name: "tom",
};
},
methods: {
setName() {
this.name = "marry";
},
},
watch: {
name: {
immediate: true,
handler: (newV, oldV) => {
console.log(`name被改变了,新的值是${newV}---旧的值是${oldV}`);
},
},
},
};
</script>
watch函数中访问data中的数据或者methods中的方法需要注意的问题
上述的例子中,若watch的回调函数是箭头函数,此时访问data中的数据或者methods中的方法会报错,原因是。解决方法是不要用箭头函数。