Search code examples
vuejs3

Reset a nested property in ref didn't update v-model


How can I reset a ref and update a v-model which is pointing to child property in my ref?

I create this initState object and set it to a ref object

const initState = {
  text: {
    value: "",
    isDirty: false,
  },
};

const form = ref(initState);

Then I create a reset function to reset value of v-model

const reset = () => {
  // doesn't work
  // form.value = initState;

  // work
  form.value = {
    text: {
      value: "",
      isDirty: false,
    },
  };
};

Here is my template

<template>
  <form>
    <input v-model="form.text.value" placeholder="enter text..." />
    <button @click.prevent="reset">reset</button>
  </form>
  <div>{{ form.text.value }}</div>
</template>

Here is my demo code https://codesandbox.io/s/beautiful-morning-ymxq3v

It didn't work if I set that ref directly by initState variable But it did successfully work if I assign object which is the same with initState

const reset = () => {
  // doesn't work
  // form.value = initState;

  // work
  form.value = {
    text: {
      value: "",
      isDirty: false,
    },
  };
};

Solution

  • This because the Objects are reference types,and you can test this

    const reset = () => {
      console.log(form.value.text.value === initState.text.value )   
      //  always be true
    };
    

    so a better way is to use function instead.

    const initState = ()=> ({
      text: {
        value: "",
        isDirty: false,
      }
    });
    const form = ref(initState ())
    const reset = () => {
      form.value = initState ()
    };