如何停止Vue 3中变量的响应性?

huangapple go评论102阅读模式
英文:

How to stop reactivity of variable in vue 3?

问题

我正在使用 Nuxt 3,并且需要停止 reactive 常量的响应性。因为我有一个 formData 对象,一旦点击提交,我需要从 formData 对象中删除一些键。

我已经将 formData 赋值给另一个变量,如 submitData = formData,并使用了 delete submitData.key,但它也会从 formData 中删除 key,而我需要保留在主要的 formData 对象中不被删除。

英文:

I am working on nuxt 3 and I need to stop the reactivity of the reactive constant. As I have one formData object and Once we click on submit I need to remove some keys from the formData object.

I have assigned formData in another variable like submitData = formData and used delete submitData.key but it removes the key from formData as well and I need that should not be removed from the main formData object

答案1

得分: 1

要实现这一点,您可以使用toRaw函数获取formData对象的原始非响应版本,然后使用响应函数创建formData对象的响应式副本并赋值给submitData变量。

演示:

import { reactive, toRaw } from 'vue';

const formData = {...}

const submitData = reactive({ ...toRaw(formData) });

delete submitData.key;
英文:

To achieve this, You can use the toRaw function to obtain the original non-reactive version of the formData object and then use the reactive function to create a reactive copy of the formData object and assign to submitData variable.

Demo :

import { reactive, toRaw } from 'vue';

const formData = {...}

const submitData = reactive({ ...toRaw(formData) });

delete submitData.key;

答案2

得分: 0

你可以创建 formData 的浅拷贝:

const submitData = { ...formData };

或者使用 lodashcloneDeep 进行深拷贝:

const submitData = _.cloneDeep(formData);

这两种方式都会创建一个新的对象,该对象具有与原始对象相同的属性和值。但是,新对象在内存中是一个独立的实体,与原始的 formData 对象不同。对副本的修改不会影响原始的 formData 对象。

英文:

You can create a shallow copy of formData

const submitData = { ...formData };

Or deep copy using cloneDeep from lodash

const submitData = _.cloneDeep(formData);

Both will create a new object with the same properties and values as the original object. However, the new object is a separate entity in memory, distinct from the original object. Modifications made to the copy won't affect the original formData object.

huangapple
  • 本文由 发表于 2023年7月17日 18:10:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定