英文:
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 };
或者使用 lodash 的 cloneDeep
进行深拷贝:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论