How to reset all values to initial state in vue3

Viewed 2271

In vue2, we can use Object.assign(this.$data, this.$options.data()) to reset all values

But how can we do the same thing (one line coding) in vue3, assuming my setup() is ....

setup(props, context) {
  let a = ref('value1')
  let b = ref('value2')
  let c = ref('value3')
  
  function reset() {
    Object.assign(????, ????) or ???? <-- ????
  }
}
1 Answers

Object.assign(this.$data, this.$options.data()) is a workaround that relies on options API internals.

It's a good practice to have reusable function for scenarios where initial state needs to be accessed more than once:

const getInitialData = () => ({ a: 1, ... });

It can be called both in data and setup.

Component state or its part can be expressed as single object. In this case it's handled the same way as Vue 2 state:

const formData = reactive(getInitialData());
...
Object.assign(formData, getInitialData());

Otherwise a.value, etc need to be assigned with respective initial values, either manually or with helper function:

let data = getInitialData();
for (let [key, ref] of Object.entries({ a, b, ... }))  
  ref.value = data[key];
Related