VUE3-watch侦听ref包裹对象
回顾响应式
ref(100)
===> RefImpl对象,引用对象(使用object.defineProperty实现)。可以监视这个引用对象。reactive
===> Proxy对象,代理对象(使用Proxy实现),可以监视这个代理对象。ref({})
===> RefImpl对象,引用对象(使用object.defineProperty + Proxy),可以监视代理对象和引用对象
关键点
watch侦听是侦听响应式对象,即RefImpl对象、Proxy对象,如果不为响应式则需要使用函数形式
代码
<template>
<div>计数器:{{counterRefImpl}}</div>
<button @click="counterRefImpl++">点我加1</button>
<div>计数器2:{{data.a.b.c.counter}}</div>
<button @click="data.a.b.c.counter++">点我加1</button>
<div>计数器3:{{data.counter}}</div>
<button @click="data.counter++">点我加1</button>
</template>
<script>
import {
ref,
watch
} from 'vue'
export default {
setup() {
let counterRefImpl = ref(1)
let data = ref({
counter: 2,
a: {
b: {
c: {
counter: 1
}
}
}
})
// 监视data
// data.value为一个代理对象
// oldValue 又是拿不到的
// deep配置无效。
watch(data.value, (newValue, oldValue) => {
console.log(newValue, oldValue);
}, {
deep: false
})
// data是一个RefImpl对象。支持deep配置的。默认是没有开启深度监视的
// watch(data, (newValue, oldValue) => {
// console.log(newValue, oldValue);
// }, {deep: true})
// watch
// 错误的, 因为counterRefImpl.value 为一个值,不是一个响应式对象
// watch(data.value.counter, (newValue, oldValue) => {})
// watch(counterRefImpl.value, (newValue, oldValue) => {})
console.log(counterRefImpl);
// 可以监视到的,使用函数形式
watch(() => data.value.counter, (newValue, oldValue) => {
console.log(newValue, oldValue);
})
watch(() => counterRefImpl.value, (newValue, oldValue) => {
console.log(newValue, oldValue);
})
return {
data,
counterRefImpl
}
}
}
</script>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9QgtFg3Q-1689761730559)(https://gitee.com/zhang_luwei/image-resources/raw/master/image/1689647918250.jpg)]
涉及内容
VUE3、ref、RefImpl、Proxy、watch