Vue 3 中 watch 的详细使用指南
在 Vue 3 中,watch 是一个用于观察和响应数据变化的强大 API。下面是关于 Vue 3 中 watch 的详细使用说明。
1.基本用法,观察单个ref数据
import { ref, watch } from 'vue'export default {setup() {const count = ref(0)// 基本 watch 用法watch(count, (newValue, oldValue) => {console.log(`count 从 ${oldValue} 变为 ${newValue}`)})return {count}}
}
2. 观察响应式对象
import { reactive, watch } from 'vue'export default {setup() {const state = reactive({count: 0,name: 'John'})// 观察整个响应式对象watch(() => state, (newState, oldState) => {console.log('state changed', newState)}, { deep: true })// 观察特定属性watch(() => state.count, (newCount, oldCount) => {console.log(`count changed: ${oldCount} -> ${newCount}`)})return {state}}
}
3.观察多个源
import { ref, watch } from 'vue'export default {setup() {const count = ref(0)const name = ref('John')watch([count, name], ([newCount, newName], [oldCount, oldName]) => {console.log(`count: ${oldCount} -> ${newCount}`)console.log(`name: ${oldName} -> ${newName}`)})return {count,name}}
}
4.常用高级选项
4.1. deep 选项
当观察对象或数组时,需要使用 deep 选项来深度观察嵌套属性的变化。
import { reactive, watch } from 'vue'export default {setup() {const user = reactive({name: 'John',address: {city: 'New York'}})watch(user, (newValue, oldValue) => {console.log('user changed', newValue)}, { deep: true })return {user}}
}
4.2 immediate 选项
immediate 选项使回调在观察开始时立即执行。
import { ref, watch } from 'vue'export default {setup() {const count = ref(0)watch(count, (newValue, oldValue) => {console.log(`count is ${newValue}`)}, { immediate: true })return {count}}
}
5. vue3官网解释
更多详情请访问vue3官网