vue可以通过watch监听data内数据的变化。通常写法是:
data: { a: 100 }, watch: { a(newval, oldVal) { // 做点什么。。。 console.log(newval, oldVal) } }
vue监听整个对象,如下:
- deep: true 深度监测
data: { return { msg: { name: 'hahah', color: 'red' } } } watch: { msg: { handler(newValue, oldValue) { // 做点什么。。。 console.log(newValue) }, deep: true }
如果监听对象内的某一具体属性,可以通过computed做中间层来实现:
computed: { name() { return this.msg.name } }, watch:{ name(newValue, oldValue) { // 做点什么。。。 console.log(newValue, oldValue) } }