一、watch简介
监听数据的变化
二、watch的使用
<template>
<h2>当前的和为:{{sum}}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前信息为:{{msg}}</h2>
<button @click="msg+='!'">修改信息</button>
</template>
<script>
import {ref,watch} from 'vue'
export default {
name: 'Demo',
setup() {
let sum = ref(0)
let msg = ref('你好啊')
let person = reactive({
name: '张三',
age: 12,
a: {
b: 12
}
})
watch([sum, msg], (newValue, oldValue) => {
console.log('sum变化', newValue, oldValue);
}, {immediate: true,deep: true})
watch([() => person.name, () => person.age], (newValue, oldValue) => {
console.log('name和age变化', newValue, oldValue);
})
watch(() => person.a, (newValue, oldValue) => {
console.log('a变化', newValue, oldValue);
},{deep:true})
return {
sum,
msg
}
}
}
</script>
引入watch,通过watch函数监听属性,监听多个属性,用数组方式监听。 当页面加载完毕,立即执行,使用immediate选项。 当需要对深层次数据进行监听,使用deep。
reactive说明
- 无法对reactive对象整体watch监视,无法获取oldValue。
- 对于reactive对象的某一数据进行监视时,通过函数监视数据。
- 对于reactive对象的某一属性深度监视时,需要使用deep选项开启监视。
ref说明
- 基本数据类型,直接监视数据
- 对象数据类型,通过.value或添加deep选项,开启监视