In the process of Vue project development, I encountered the need to reuse the data in data, but the data in data has been assigned value change, how to reset the value of data to the initial state?

Solutions:

1. Direct assignment (not recommended, if multiple places need to reset the data, resulting in a large number of redundant code)
This. form = {data to set}Copy the code
2. Use this.$options.data() to get the value of the initial data, and then use Object.assign() to copy the Object.

This.$data: Get the data in the current state, that is, the data to be changed; This.$options.data(): Vue's original data, which is the data when the page was first loaded

Object.assign(this.$data, this.$options.data())
Copy the code

If you need to reset a specific data (eg: form), use the following method, eg:
Object.assign(this.$data.form, this.$options.data().form)
Copy the code

3. Use global variables

Attention!

If this is used to access props or methods, and this.$options.data() is used to reset data, the props or method of data() obtained by this is undefined. Note that this.$options.data() points to this.$options.data.call(this).