当前位置: 首页 > news >正文

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

http://www.xdnf.cn/news/640423.html

相关文章:

  • 什么是智能体agent?
  • Anaconda 常用命令汇总
  • Mongo DB | 多种修改数据库名称的方式
  • 明阳智慧能源社招校招入职测评 |iLogic言语逻辑数字、Talent5大五职业性格测评、TAS倍智人才测评考什么
  • 资源-又在网上淘到金了-三维模型下载
  • CodeTop之LRU缓存
  • SQL JOIN
  • 4款顶级磁力下载工具,速度提升器,可以变下变播
  • 【RocketMQ 生产者和消费者】- 生产者发送故障延时策略
  • MATLAB在逐渐被Python淘汰吗
  • 【Java高阶面经:缓存篇】35、 Redis单线程 vs Memcached多线程:高性能内存数据库设计解析
  • ComfyUI进行海报创作
  • 【Linux 学习计划】-- 冯诺依曼体系 | 操作系统的概念与定位,以及其如何管理软件
  • Reactor模式详解:高并发场景下的事件驱动架构
  • ROI智能计算精灵
  • Google 推出 Flow —— AI 电影制作新平台
  • 浏览器游戏的次世代革命:WebAssembly 3.0 实战指南
  • 微雪2.7英寸墨水屏 API函数 解释
  • 大模型BERT登顶刊CAR!分析专利文本的作用
  • 开源项目跨平台桌宠 BongoCat,为桌面增添乐趣!
  • SEO搜索引擎优化
  • log日志最佳实践
  • Mybatis框架的构建(IDEA)
  • 计算机网络学习(七)——IP
  • LangChain03-图数据库与LangGraph
  • JWT与布隆过滤器结合使用指南
  • 【数学基础】范数及其应用
  • Leetcode 刷题记录 10 —— 二叉树
  • 第五项修炼与系统思考
  • Lambda表达式的方法引用详解