vue3中使用watch

Vue 3 中 watch 的详细使用指南

在 Vue 3 中,watch 是一个用于观察和响应数据变化的强大 API。下面是关于 Vue 3 中 watch 的详细使用说明。

1.基本用法,观察单个ref数据

javascript 复制代码
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. 观察响应式对象

javascript 复制代码
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.观察多个源

javascript 复制代码
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 选项来深度观察嵌套属性的变化。

javascript 复制代码
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 选项使回调在观察开始时立即执行。

javascript 复制代码
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官网

相关推荐
roamingcode1 小时前
前端 AI Agent 多智能体协作架构:从对抗式排查到工作流解耦
前端·人工智能·架构·agent·team
蓝莓味的口香糖2 小时前
【vue】初始化 Vue 项目
前端·javascript·vue.js
aikongmeng2 小时前
【Ai】Claude Code 初始化引导
javascript
光影少年3 小时前
数组去重方法
开发语言·前端·javascript
我命由我123453 小时前
浏览器的 JS 模块化支持观察记录
开发语言·前端·javascript·css·html·ecmascript·html5
weixin_443478513 小时前
Flutter第三方常用组件包之路由管理
前端·javascript·flutter
武藤一雄4 小时前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
啥都不懂的小小白4 小时前
前端CSS入门详解
前端·css
林恒smileZAZ4 小时前
前端大屏适配方案:rem、vw/vh、scale 到底选哪个?
开发语言·前端·css·css3
QQ5110082854 小时前
基于区块链的个人医疗咨询挂号信息系统vue
前端·vue.js·区块链