Vue3的watch监听器
时间: 2023-11-01 15:57:38 浏览: 101
vue.js watch监听,vue.js 监听watch
Vue3的watch监听器有以下几种用法:
1. 监听基础数据类型:
```javascript
watch(count, (newValue, oldValue) => {
console.log("已触发count:", newValue);
});
```
2. 监听复杂数据类型中的某个属性:
```javascript
watch(() => state.account, (newValue, oldValue) => {
console.log("state.account已触发:", newValue);
});
```
3. 只监听复杂数据类型中的子属性:
```javascript
watch(() => ({ ...state }), (newValue, oldValue) => {
console.log("state子属性已触发:", newValue);
});
```
4. 监听整个对象,包括子、孙属性的改变:
```javascript
watch(() => state, (newValue, oldValue) => {
console.log("state子孙改变都会触发:", newValue);
}, { deep: true });
```
5. 组合监听多个数据源:
```javascript
watch([() => state.account, state, count], ([newAccount, newState, newCount], [oldAccount, oldState, oldCount]) => {
console.log("已触发newAccount:", newAccount);
console.log("已触发newState:", newState);
console.log("已触发newCount:", newCount);
});
```
以上是Vue3中watch监听器的几种用法,可以根据需求选择适合的方式进行监听。
阅读全文