Vue resets the data of data to the initial state operation

  • 2021-11-01 23:10:45
  • OfStack

In some cases, the data in data needs to be reused, but the data in data has been assigned to various forms, variables, etc. How to reset the value of data?

1. Assign values one by one


...
data() {
 return {
 name: '',
 sex: '',
 desc: ''
 }
}
...
//  Assign values one by one 
this.name = ''
this.sex = ''
this.desc = ''

This method is stupid, of course, can also achieve results, but one to re-assignment more troublesome and the code will look messy.

The following method is definitely what you like, 1 line of code is done ~

2. Use Object. assign ()

MDN Introduction to this method: The Object. assign () method is used to copy the values of all enumerable properties from one or more source objects to the target object. It returns the target object.

Usage: Object. assign (target,... sources)

The first parameter is the target object, and the second parameter is the source object, that is, copying the properties of the source object to the target object and returning the target object

In this case, the attribute copy of one object is applied to another object

In vue:

this. $data Get data in the current state

this. $options. data () Gets the data of the component in its initial state

Therefore, you can copy the data in the initial state to the data in the current state to achieve the reset effect:


Object.assign(this.$data, this.$options.data())

Of course, if you only want to reset one object or property in data:


this.form = this.$options.data().form

Expand

The Object. assign (target,... sources) methods can also be used to merge objects:


const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 },  Note that the target object itself will change. 

If the object contains the same property, take the last property:


const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };
const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }  Attribute takes the last 1 Attributes of objects 

Related articles: