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

相关推荐
一拳不是超人16 分钟前
DeepSeek Harness 为什么敢说"一切皆插件"?拆透 Cordis 引擎的五大核心机制
前端·人工智能·agent
IT_陈寒28 分钟前
Python的GIL让我多写了500行代码
前端·人工智能·后端
风骏时光牛马28 分钟前
AI智能体能力调度微服务
前端
Eloudy2 小时前
ReAct 原理简介
前端·javascript·人工智能·react.js·agent·gpu
ZJU_统一阿萨姆3 小时前
【DSH】如何将 DeepSeek Harness 嵌入生产环境?万字解构 DeepSeek Agent Harness 的运行机制与安全边界
前端·javascript·安全
用户921080262863 小时前
4. 前端地图大量点位实时更新优化:后端推增量,前端做 diff
前端
SoaringHeart4 小时前
Flutter最佳实践:Web项目中文字体首次加载乱码问题解决
前端·flutter
西安小哥4 小时前
破局与重生:大厂前端如何借力 AI 转型“超级全栈“
前端·人工智能
sunly_5 小时前
TypeScript总结:16、面向对象速查
前端·javascript·typescript
张元清5 小时前
React useInterval Hook:没有过期闭包的 setInterval (2026)
javascript·react.js