注意:监听的对象必须已经在data中声明了
data: { a: 1, b: 2, c: 3, d: 4, e: { f: { g: 5 } } }, watch: { a: function (val, oldVal) { console.log('new: %s, old: %s', val, oldVal) }, // string method name b: 'someMethod', // deep watcher e: { handler: function (val, oldVal) { /* ... */ }, deep: true }, // the callback will be called immediately after the start of the observation d: { handler: function (val, oldVal) { /* ... */ }, immediate: true }, e: [ function handle1 (val, oldVal) { /* ... */ }, function handle2 (val, oldVal) { /* ... */ } ], // watch vm.e.f's value: {g: 5} 'e.f': function (val, oldVal) { /* ... */ } } }) vm.a = 2 // => new: 2, old: 1
比如下面例子
//监听某个变量 watch: { bet(newValue, oldValue) { console.log(newValue); } } //监听对象 某一个属性 watch: { 'bet.text': function (val, oldVal) {} }
//监听 整个对象(数组) serviceList:{ handler(){ //注意此处就是handler console.log(this.serviceList); }, deep:true, immediate: true // watch 的一个特点是,最初绑定的时候是不会执行的,要等到 serviceList 改变时才执行监听计算。加上改字段让他最初绑定的时候就执行 },