位置:- 正文

Vue3 reactive丢失响应式问题(vuex状态丢失)

编辑:rootadmin
Vue3 reactive丢失响应式问题

推荐整理分享Vue3 reactive丢失响应式问题(vuex状态丢失),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:vue数据丢失,vue3 reactive ref,vue3.0 reactive,vuex数据丢失怎么处理,vue3.0 reactive,vue报错文件找不到,vue3 reactive不能,vue数据丢失,内容如对您有帮助,希望把文章链接给更多的朋友!

问题描述:使用 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 定义的对象失去了响应式,这是什么原因呢?官网中写到:

Vue3 reactive丢失响应式问题(vuex状态丢失)

如果将一个对象赋值给 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>

本文链接地址:https://www.jiuchutong.com/zhishi/299456.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/299457.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络