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

相关推荐
橙序员小站2 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名5 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫5 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊5 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter5 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折5 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_5 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码15 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial5 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu6 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端