vue2watch监听多个变量
时间: 2023-08-14 09:14:35 浏览: 133
Vue开发之watch监听数组、对象、变量操作分析
在Vue2中,watch本身无法直接监听多个变量。但是我们可以通过计算属性返回一个包含需要监听的多个变量的对象,然后再监听这个对象来实现"监听多个变量"的效果。具体的代码如下所示:
```javascript
export default {
data() {
return {
msg1: 'apple',
msg2: 'banana'
}
},
computed: {
msgObj() {
const { msg1, msg2 } = this
return { msg1, msg2 }
}
},
watch: {
msgObj: {
handler(newVal, oldVal) {
if (newVal.msg1 !== oldVal.msg1) {
console.log('msg1 has changed')
}
if (newVal.msg2 !== oldVal.msg2) {
console.log('msg2 has changed')
}
},
deep: true
}
}
}
```
在上述代码中,我们通过计算属性`msgObj`返回一个包含`msg1`和`msg2`的对象。然后在`watch`选项中监听`msgObj`,并在`handler`中判断`msg1`和`msg2`的变化情况进行相应的处理。通过设置`deep: true`来深度监听对象的变化。
这样,当`msg1`或`msg2`发生变化时,就会触发相应的处理逻辑。
#### 引用[.reference_title]
- *1* [VUE的watch监听多个变量](https://blog.csdn.net/CSDN877425287/article/details/115709040)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [vue watch监听多个数据](https://blog.csdn.net/weixin_51033461/article/details/128728364)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文