ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

VUE3使用watch监测数据变化

2022-07-09 09:34:05  阅读:226  来源: 互联网

标签:监测数据 console name 数据源 watch userInfo VUE3 log


 1 // 不要忘了导入要用的 API
 2 import { defineComponent, reactive, watch } from 'vue'
 3 
 4 export default defineComponent({
 5   setup() {
 6     // 定义一个响应式数据
 7     const userInfo = reactive({
 8       name: 'Petter',
 9       age: 18,
10     })
11 
12     // 2s后改变数据
13     setTimeout(() => {
14       userInfo.name = 'Tom'
15     }, 2000)
16 
17     /**
18      * 可以直接监听这个响应式对象
19      * callback 的参数如果不用可以不写
20      */
21     watch(userInfo, () => {
22       console.log('监听整个 userInfo ', userInfo.name)
23     })
24 
25     /**
26      * 也可以监听对象里面的某个值
27      * 此时数据源需要写成 getter 函数
28      */
29     watch(
30       // 数据源,getter 形式
31       () => userInfo.name,
32       // 回调函数 callback
33       (newValue, oldValue) => {
34         console.log('只监听 name 的变化 ', userInfo.name)
35         console.log('打印变化前后的值', { oldValue, newValue })
36       }
37     )
38   },
39 })

 

批量监测

 

 1 import { defineComponent, ref, watch } from 'vue'
 2 
 3 export default defineComponent({
 4   setup() {
 5     // 定义多个数据源
 6     const message = ref<string>('')
 7     const index = ref<number>(0)
 8 
 9     // 2s后改变数据
10     setTimeout(() => {
11       message.value = 'Hello World!'
12       index.value++
13     }, 2000)
14 
15     watch(
16       // 数据源改成了数组
17       [message, index],
18       // 回调的入参也变成了数组,每个数组里面的顺序和数据源数组排序一致
19       ([newMessage, newIndex], [oldMessage, oldIndex]) => {
20         console.log('message 的变化', { newMessage, oldMessage })
21         console.log('index 的变化', { newIndex, oldIndex })
22       }
23     )
24   },
25 })

 

来自于: https://vue3.chengpeiquan.com/component.html#基础用法

 

标签:监测数据,console,name,数据源,watch,userInfo,VUE3,log
来源: https://www.cnblogs.com/googlegis/p/16460179.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有