3

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

8

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.