属性的侦听方式有两种:
1、实例中的watch属性
2、vm1.$watch
参考代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>监听属性变化</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="text" v-model="nVal"> <button @click="age = 180">点击改变age值</button> <!--点击button按钮之后 age属性发生变化,触发对应的函数--> </div> </body> </html> <script> // 监听方式一 let vm1 = new Vue({ el: '#app', data: { nVal: '', age: 100 }, watch: { // 不断的监测nVal的变化,nVal变化之后,便会触发下面的函数 nVal: function (newValue, oldValue) { // 其中newValue表示改变之后的值, oldvalue表示改变之前的值 console.log("nVal变化触发该函数",newValue, oldValue); }, // 如果age发生变化, 这个函数就会执行 age: function (newValue, oldValue) { console.log("age变化触发该函数",newValue, oldValue); } } }); // 监听方式二 let unWatch = vm1.$watch('age', function (newValue, oldValue) { console.log('vm1监听方式', newValue, oldValue) }); // 移除监听,在组件化开发时,在组件销毁的钩子中调用 // unWatch(); </script>