视频内容
watchEffect函数
watch的套路是:既要指明监视的属性,也要指明监视的回调。
watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性。
watchEffect有点像computed:
- 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。
- 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。
//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
watchEffect(()=>{
const x1 = sum.value
const x2 = person.age
console.log('watchEffect配置的回调执行了')
})
源码
components\Demo.vue
<template>
<h2>当前求和为:{{sum}}</h2>
<button @click="sum++">点我+1</button>
<hr>
<h2>当前的信息为:{{msg}}</h2>
<button @click="msg+='!'">修改信息</button>
<hr>
<!-- 演示情况3 -->
<h2>姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}}</h2>
<h2>薪资:{{person.job.j1.salary}}K</h2>
<button @click="person.name+='~'">修改姓名</button>
<button @click="person.age++">增长年龄</button>
<button @click="person.job.j1.salary++">涨薪</button>
</template>
<script>
import {ref,reactive,watch, watchEffect} from 'vue'
export default {
name: 'Demo',
setup(){
//数据
let sum = ref(0)
let msg = ref('你好啊')
let person = reactive({ //如果此处写成 ref({}) 来定义 对象,实际上在ref()里面还是调用的 reactive()
name:'张三',
age:18,
job:{
j1:{
salary:20
}
}
})
//输出为 RefImpl 实例对象,简称为 Ref对象
console.log(sum) // sum.value ∈ 基本类型的值
console.log(msg) // msg.value ∈ 基本类型的值
console.log(person) //person.value ∈ Proxy(求助reactive,变为了 reactive 生成的一个代理对象)
//监视:
/*watch(sum,(newValue,oldValue)=>{ //实测有效果
console.log('sum的值变化了', newValue, oldValue)
},{immediate:true})*/
//最大的特点: 不说监视的是谁
//watchEffect() 很智能: 你用谁,它就监视谁。
watchEffect(()=>{
const x1 = sum.value
const x2 = person.job.j1.salary
console.log('watchEffect所指定的回调执行了')
})
//返回一个对象(常用)
return {
sum,
msg,
person
}
}
}
</script>
