vue选项式中watch深度监听的写法
时间: 2023-07-18 14:42:19 浏览: 47
在Vue选项式中,可以通过`watch`选项的第二个参数来开启深度监听。第二个参数可以是一个布尔值或一个对象,其中`deep`属性表示是否开启深度监听。如果`deep`属性为`true`,则表示开启深度监听。
下面是一个示例:
```javascript
import { watch } from 'vue';
export default {
data() {
return {
message: 'Hello Vue!',
data: {
name: 'Tom',
age: 20
}
};
},
setup() {
watch(
() => data,
(newVal, oldVal) => {
console.log('data对象或子属性发生变化');
},
{ deep: true }
);
}
};
```
在上述示例中,使用了Vue 3中的`watch`函数来实现深度监听。在`watch`函数的第三个参数中开启了`deep`属性,当`data`对象或其子属性发生变化时,`watch`函数的第二个参数就会被触发。
需要注意的是,在Vue 3中,选项式API和组合式API的写法有所不同,需要根据具体的情况来选择使用哪种API。如果需要在组件中使用组合式API,需要使用`setup`函数来实现。
相关问题
vue3watch深度监听的写法
在 Vue 3 中,你可以使用 `watch` 函数来实现深度监听。下面是一个简单的例子:
```javascript
import { ref, watch } from 'vue'
const data = ref({
message: 'Hello Vue 3!',
nested: {
value: 0
}
})
watch(data, (newVal, oldVal) => {
console.log('Data changed!', newVal, oldVal)
}, { deep: true })
// 修改嵌套属性
data.value.nested.value = 1 // 输出: Data changed! { message: 'Hello Vue 3!', nested: { value: 1 } } { message: 'Hello Vue 3!', nested: { value: 0 } }
// 修改对象属性
data.value.message = 'Hello World!' // 输出: Data changed! { message: 'Hello World!', nested: { value: 1 } } { message: 'Hello Vue 3!', nested: { value: 1 } }
```
在上面的例子中,我们使用 `watch` 函数来监听 `data` 的变化。当 `data` 中的属性发生变化时,回调函数会被触发。我们设置了 `deep` 选项为 `true`,以启用深度监听。这样,当 `data` 中的嵌套属性或子属性发生变化时,也会触发回调函数。
需要注意的是,Vue 3 中的 `watch` 函数返回一个 `stop` 函数,可以用于停止监听。例如:
```javascript
const stop = watch(data, (newVal, oldVal) => {
console.log('Data changed!', newVal, oldVal)
}, { deep: true })
// 停止监听
stop()
```
vue3+ts深度监听watch用法组合式写法
在 Vue 3 中,可以使用组合式 API 进行开发。组合式 API 提供了 `watch` 函数,可以用来深度监听响应式数据的变化。同时,由于使用 TypeScript 进行开发,我们需要使用泛型来确定要监听的数据类型。下面是一个示例代码:
```typescript
import { defineComponent, watch, Ref } from 'vue';
interface Address {
city: string;
district: string;
}
interface Person {
name: string;
age: number;
address: Address;
}
export default defineComponent({
setup() {
const person: Ref<Person> = ref({
name: 'Tom',
age: 18,
address: {
city: 'Beijing',
district: 'Haidian'
}
});
watch(
() => person.value,
(newVal: Person, oldVal: Person) => {
console.log('person 发生了变化');
},
{ deep: true }
);
watch(
() => person.value.address,
(newVal: Address, oldVal: Address) => {
console.log('person.address 发生了变化');
},
{ deep: true }
);
return {
person
};
}
});
```
在上面的示例中,我们定义了 `Person` 和 `Address` 两个接口来确定要监听的数据类型。然后使用 `defineComponent` 函数来定义组件,并在 `setup` 函数中定义响应式数据 `person`。接着,使用 `watch` 函数来深度监听 `person` 和 `person.address` 的变化。由于使用了 TypeScript,我们需要在回调函数中指定 `newVal` 和 `oldVal` 的类型。最后,将 `person` 对象返回以便在模板中使用。