skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search