Vue3中reactive丢失响应式问题详解

问题描述:

使用 reactive 定义的对象,重新赋值后失去了响应式,改变值视图不会发生变化。

测试代码:

<template>
 <div>
 <p>{{ title }}</p>
 <ul>
 <li v-for="(item, index) in tableData" :key="index">{{ item }}</li>
 </ul>
 </div>
</template>
 
<script setup>
 import { ref, reactive, onMounted } from 'vue'
 
 const title = ref('我是标题')
 let tableData = reactive([1, 2, 3])
 
 onMounted(() => {
 title.value = '我是段落',
 tableData = [1, 1, 1]
 console.log("title=", title)
 console.log("tableData=", tableData)
 }) 
</script>

输出结果:

从上述测试代码中,ref 定义的对象有响应式,而 reactive 定义的对象失去了响应式,这是什么原因呢?官网中写到:

如果将一个对象赋值给 ref ,那么这个对象将通过 reactive() 转为具有深层次响应式的对象。

那么,为什么 ref 调用 reactive 处理对象重新赋值后,不会丢失响应式,但 reactive 却丢失了呢?

第一步:当我们修改 xxx.value 值的时候,setter 调用了 toReactive 方法

class RefImpl {
 constructor(value, __v_isShallow) {
 this.__v_isShallow = __v_isShallow;
 this.dep = undefined;
 this.__v_isRef = true;
 this._rawValue = __v_isShallow ? value : toRaw(value);
 this._value = __v_isShallow ? value : toReactive(value);
 }
 get value() {
 trackRefValue(this);
 return this._value; // get方法返回的是_value的值
 }
 set value(newVal) {
 newVal = this.__v_isShallow ? newVal : toRaw(newVal);
 if (hasChanged(newVal, this._rawValue)) {
 this._rawValue = newVal;
 this._value = this.__v_isShallow ? newVal : toReactive(newVal); // set方法调用 toReactive 方法
 triggerRefValue(this, newVal);
 }
 }
}

 第二步:toReactive 方法判断是否是对象,是的话就调用 reactive 方法

const toReactive = (value) => isObject(value) ? reactive(value) : value;

 第三步:reactive 方法,先判断数据是否是“只读”的,不是就返回 createReactiveObject() 方法处理后的数据(createReactiveObject 方法将对象通过 proxy 处理为响应式对象)

function reactive(target) {
 // if trying to observe a readonly proxy, return the readonly version.
 if (isReadonly(target)) {
 return target;
 }
 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
}

结论:

ref 定义数据(包括对象)时,都会变成 RefImpl(Ref 引用对象) 类的实例,无论是修改还是重新赋值都会调用 setter,都会经过 reactive 方法处理为响应式对象。

但是 reactive 定义数据(必须是对象),是直接调用 reactive 方法处理成响应式对象。如果重新赋值,就会丢失原来响应式对象的引用地址,变成一个新的引用地址,这个新的引用地址指向的对象是没有经过 reactive 方法处理的,所以是一个普通对象,而不是响应式对象。

如何正确使用 reactive 呢?

使用 reactive 定义数据时,使用对象包含键值对的形式,那么就会避免重新赋值的问题。那么,修改测试代码为:

<template>
 <div>
 <p>{{ title }}</p>
 <ul>
 <li v-for="(item, index) in obj.tableData" :key="index">{{ item }}</li>
 </ul>
 </div>
</template>
 
<script setup>
 import { ref, reactive, onMounted } from 'vue'
 
 const title = ref('我是标题')
 let obj = reactive({
 tableData: [1, 2, 3]
 })
 
 onMounted(() => {
 title.value = '我是段落',
 obj.tableData = [1, 1, 1]
 }) 
</script>

总结

作者:Baobao小包原文地址:https://blog.csdn.net/forever__fish/article/details/127675308

%s 个评论

要回复文章请先登录注册