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

How to properly reset Vue Composition Api's reactive values


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: "john@doe.com"      });    }    return { form, setForm, resetForm };  }

See it live on codesandbox

credits: taken from here


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)


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: "john@doe.com"}) {        // only loop with the supported keys of initial state        for (const key of Object.keys(initialState)) {          form[key] = values[key]        }    }    return { form, setForm, resetForm };  }