The watch function and the watchEffect function are both listeners. There are certain differences in writing and usage. They are two different forms of the same function, but the bottom layer is the same. [Related recommendations: vue.js video tutorial]
watch
Explicitly specify the dependent data. When the dependent data is updated, executes the callback function.
immediate: true
, it can become non-lazy, and the page will be executed when it is first loaded) watchEffect
Automatically collect dependencies Data, when the data is updatedRe-executes itself
Immediately, there is no inertia, it will be executed when the page is loaded for the first time
The original value cannot be obtained, only the changed value
There is no need to specify which attribute to monitor, whichever attribute is used in the monitoring callback will be monitored
The watch function has two pitfalls:
Monitoring the responsive data defined by reactive (The data is an object, because reactive can only define responses of array or object types): oldValue cannot be obtained correctly, and deep monitoring will be forced to be turned on, and the deep configuration will not take effect.
When monitoring an attribute in the responsive data defined by reactive, and the attribute is an object, then the deep configuration will take effect.
The specific usage of the watch function is reflected in the following code, with detailed comments
<template> <div> <h2>当前求和为:{{sum}}</h2> <button @click="sum++">点我+1</button> <hr> <h2>当前的信息为:{{msg}} </h2> <!-- 点击button拼接! --> <button @click="msg+='!'">修改数据</button> <hr> <h2>姓名:{{person.name}}</h2> <h2>年龄:{{person.age}}</h2> <h2>薪资:{{person.job.j1.salary}}</h2> <button @click="person.name+='~'"> 修改姓名</button> <button @click="person.age++"> 增长年龄</button> <button @click="person.job.j1.salary++"> 增长薪资</button> </div> </template> <script> import {ref,reactive,watch,watchEffect} from 'vue' export default { name:'demo', setup(){ //数据 let sum = ref(0) let msg = ref('hello') let person = reactive({ name:'zhangsan', age:'18', job:{ j1:{ salary:20 } } }) //监视(三个参数,第一个是监视的对象,第二个是监视的回调函数,第三个是监视的配置) //情况一:监视ref所定义的一个响应式数据 watch(sum,(newValue,oldValue)=>{ console.log('sum的值变化了',newValue,oldValue) },{immediate:true,deep:true}) //immediate的值为true时表示非惰性的立即执行的(默认情况下是false) //deep深层次触发(此处设置deep无意义) //情况二:监视ref所定义的多个响应式数据,写成数组的形式 watch([sum,msg],(newValue,oldValue)=>{ console.log('sum或者msg变了',newValue,oldValue) }) //情况三:监视reactive所定义的响应式数据 //若监视的是reactive定义的响应式数据,则无法正确获得oldValue //若监视的是reactive定义的响应式数据,则watch会强制开启深度监视 //我们发现改变person的任意一个属性都会被监视到 watch(person,(newValue,oldValue)=>{ console.log('person改变了',newValue,oldValue) }) //我们尝试设置deep:false,关闭深度监听(目的:改变job的值不会被watch监听到) //但是我们发现deep:false并没有生效,原因是此时watch监视的是reactive定义的响应式对象,默认强制开启了深度监听 watch(person,(newValue,oldValue)=>{ console.log('person改变了',newValue,oldValue) },{deep:false}) //情况四:监视reactive所定义的响应式数据中的某个属性 watch(()=>person.name,(newValue,oldValue)=>{ console.log('person的job改变了',newValue,oldValue) }) watch(()=>person.age,(newValue,oldValue)=>{ console.log('person的job改变了',newValue,oldValue) }) watch(()=>person.job,(newValue,oldValue)=>{ console.log('person的job改变了',newValue,oldValue) }) //从上边我们发现改变name,age都会触发监听,但是改变job不会 //这是因为name和age属性的值只是一个简单的基本类型数据, //而job属性的值是一个对象,比较深,想要监视到,就要开启深度监视,程序如下: watch(()=>person.job,(newValue,oldValue)=>{ console.log('person的job改变了',newValue,oldValue) },{deep:true})//此时job改变,会被监视到,此处的deep配置生效 //需要和情况三进行区分,此处watch监视的是reactive所定义的对象中的某个属性,而情况三watch监视的是reactive所定义的对象 //情况五:监视reactive所定义的响应式数据中的某些属性,写成数组的形式 watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{ console.log('person的name或age改变了',newValue,oldValue) }) //返回一个对象(常用) return{ sum, msg, person } } } </script>
watch cancel monitoring
const stop1 = watch( [() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => { console.log(curName, curEng, "----", prevName, curEng); setTimeout(() => { stop(); }, 5000); });
The function usage is shown in the following code, with detailed comments:
<template> <div> <h2>当前求和为:{{sum}}</h2> <button @click="sum++">点我+1</button> <hr> <h2>当前的信息为:{{msg}} </h2> <!-- 点击button拼接! --> <button @click="msg+='!'">修改数据</button> <hr> <h2>姓名:{{person.name}}</h2> <h2>年龄:{{person.age}}</h2> <h2>薪资:{{person.job.j1.salary}}</h2> <button @click="person.name+='~'"> 修改姓名</button> <button @click="person.age++"> 增长年龄</button> <button @click="person.job.j1.salary++"> 增长薪资</button> </div> </template> <script> import {ref,reactive,watch,watchEffect} from 'vue' export default { name:'demo', setup(){ //数据 let sum = ref(0) let msg = ref('hello') let person = reactive({ name:'zhangsan', age:'18', job:{ j1:{ salary:20 } } }) //watchEffect函数内部所指定的回调中用到的数据只要发生变化,就会重新执行回调 //只有一个参数,就是回调 watchEffect(()=>{ const x1 = sum.value//因为sum是ref定义的响应式数据,需要使用.value调用 const x2 = person.age console.log('watchEffect配置的回调执行了') }) return{ sum, msg, person } } } </script>
watchEffect cancel monitoring
const stop = watchEffect(() => { console.log(nameObj.name); setTimeout(() => { stop(); }, 5000);});
watchEffect is a bit like computed:
But computed focuses on the calculated value (the return value of the callback function), So the return value must be written.
And watchEffect pays more attention to the process (the function body of the callback function), so there is no need to write a return value.
computed will not be called if the value is not used, but watchEffect will always be called once
Example:
<template> <div> <h2>当前求和为:{{sum}}</h2> <button @click="sum++">点我+1</button> <hr> <h2>当前的信息为:{{msg}} </h2> <!-- 点击button拼接! --> <button @click="msg+='!'">修改数据</button> <hr> <h2>姓名:{{person.name}}</h2> <h2>年龄:{{person.age}}</h2> <h2>薪资:{{person.job.j1.salary}}</h2> <button @click="person.name+='~'"> 修改姓名</button> <button @click="person.age++"> 增长年龄</button> <button @click="person.job.j1.salary++"> 增长薪资</button> </div> </template> <script> import {ref,reactive,watch,watchEffect, computed} from 'vue' export default { name:'demo', setup(){ //数据 let sum = ref(0) let msg = ref('hello') let person = reactive({ name:'zhangsan', age:'18', job:{ j1:{ salary:20 } } }) let person1 = reactive({ firstName:'张', lastName:'三' }) //computed //计算属性——简写(没有考虑计算属性被修改的情况) person1.fullName = computed(()=>{ //必须含有返回值 return person1.firstName+'-'+person1.lastName }) //计算属性——完整写法(考虑读和写) person1.fullName = computed({ //必须含有返回值 get(){ return person1.firstName+'-'+person1.lastName }, set(value){ const nameArr = value.split('-') person1.firstName = nameArr[0] person1.lastName = nameArr[1] } }) //watchEffect //可以不写给返回值 watchEffect(()=>{ const x1 = sum.value//因为sum是ref定义的响应式数据,需要使用.value调用 const x2 = person.age console.log('watchEffect配置的回调执行了') }) return{ sum, msg, person, person1 } } } </script>
The above is the detailed content of An article explaining the difference between watch and watchEffect in Vue. For more information, please follow other related articles on the PHP Chinese website!