计算属性允许我们声明性地计算衍生值。然而在有些情况下,我们需要在状态变化时执行一些“副作用”:例如更改 DOM,或是根据异步操作的结果去修改另一处的状态。
在组合式 API 中,我们可以使用 watch 函数在每次响应式状态发生变化时触发回调函数:
<script>
export default {
data() {
return {
message:"hellworld",
age:0,
user:{
name:"张三",
sex:"男"
}
}
},
methods:{
},
watch:{ //监听数据的变化
// message:function (newValue,oldValue){
// console.log(newValue);
// console.log(oldValue);
// //执行异步操作,或者复杂的代码逻辑
// if(newValue.length<5 || newValue.length>10){
// console.log("输入的值不能小于5或者大于10");
// }
//
// }
// message:{
// immediate:true, //初始化的时候调用函数
// handler:function (newValue){
// //执行异步操作,或者复杂的代码逻辑
// if(newValue.length<5 || newValue.length>10){
// console.log("输入的值不能小于5或者大于10");
// }
//
// }
// }
//监听不到对象的属性值变化,需要使用到深度监听deep
// user:{
// handle:function (newValue){
// console.log(newValue)
// },
// deep:true,//表示是否深度监听,侦听器会一层层的向下遍历,给对象每个属性都加上侦听器
// }
"user.name":{
handler:function (newValue){
console.log(newValue);
},
deep:true,//表示是否深度监听,侦听器会一层层的向下遍历,给对象每个属性都加上侦听器
}
}
}
</script>
<template>
<div>
{
{message}}<br/>
<button @click="message='哈哈'">message值发生改变</button>
</div>
</template>
<style scoped>
</style>