欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > vue3中使用watch

vue3中使用watch

2025/5/26 7:09:33 来源:https://blog.csdn.net/qq_74351687/article/details/148202061  浏览:    关键词:vue3中使用watch

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官网

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词