'How to properly reset Vue Composition Api's reactive values

I'm wondering how should I reset a reactive in vuejs setup? (i know if change it to the ref and using view.value will solve this problem, but there should be an answer to this for using reactive)

enter image description here



Solution 1:[1]

You can use Object.assign:

  setup() {
    const initialState = {
      name: "",
      lastName: "",
      email: ""
    };

    const form = reactive({ ...initialState });

    function resetForm() {
      Object.assign(form, initialState);
    }

    function setForm() {
      Object.assign(form, {
        name: "John",
        lastName: "Doe",
        email: "[email protected]"
      });
    }

    return { form, setForm, resetForm };
  }

See it live on codesandbox

credits: taken from here

Solution 2:[2]

Object.assign didn't work for me. (Maybe because I used a shim for the Composition API in Nuxtjs 2?) For anybody that run into the same problem: I had to use a compact loop.

  setup() {
    const initialState = {
      name: "",
      lastName: "",
      email: ""
    };

    const form = reactive({ ...initialState });

    function resetForm() {
        for (const [key, value] of Object.entries(initialState)) {
          form[key] = value
        }
    }

    function setForm(values = {name: "John", lastName: "Doe", email: "[email protected]"}) {
        // only loop with the supported keys of initial state
        for (const key of Object.keys(initialState)) {
          form[key] = values[key]
        }
    }

    return { form, setForm, resetForm };
  }

Solution 3:[3]

Citing from the official Vueland Discord server:

"For what I know, reactive is the old way we use to do reactivity from the Classic API, so to reset the values should be something like:"

const myData = reactive({
  foo: true,
  bar: ''
})

function resetValues () {
 myData.foo = true
 myData.bar = ''
}

Therefore, if you don't change properties you should be able to use Object.assign(). (Correct me if I'm wrong)

Solution 4:[4]

How about use ref instead of reactive?

const myData = ref({ xxx: 11 })

// ... After many operations on myData 

// resetData
myData.value = { xxx: 11 }

The disadvantage is that you need to add .value when using it in script. But this is the same as reactive in vue template.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roland
Solution 2 Markus Madeja
Solution 3 nook
Solution 4 pppppu