vue Avoids Bidirectional Binding after Variable Assignment

  • 2021-09-12 00:29:43
  • OfStack

For example: this. list = this. list2. As a result, list2 changes after list changes, which is not the desired effect

Type 1:

Using JSON. parse and JSON. stringify

this.list= JSON.parse( JSON.stringify(this.list2) )

Type 2:

Parsing Syntax of ES6

this.list= { ...this.list2}

this.arr= [...this.arr2]

Additional knowledge: Solve v-model bind variable assignment to another variable in vue, two variables change at the same time

Let's look at the background of the problem first

We want to do a search + paging function using vue

We bind the paging control to the click event, and submit the formData form bound by v-model after clicking, but we ignore one problem, that is, when the input information changes, we don't click search, click the paging control directly, and submit the search criteria in the new search box. This is not logical.

Therefore, we added a new form object submitForm to data. Only when we click Query, the formData form bound by v-model will be assigned to this object, and submitForm will be submitted when turning pages. This solves the problem.


data() {
  return {
  formData: {
   timeStart: '',
   timeEnd: '',
   //  Pagination data 
   pageNo: 1,
   pageSize: 10
  },
  submitForm: {
   timeStart: '',
   timeEnd: '',
   //  Pagination data 
   pageNo: 1,
   pageSize: 10
  },
 }

this.submitForm = this.formData
//  Use  new Also 1 Sample can't achieve results 
this.submitForm = new Object(this.formData)

But! ! !

submitForm has changed with it

This is because in Object assignments, instead of values, references are passed, and they point to the same space!

Solve

Type 1: Using JSON. parse and JSON. stringify

this.submitForm = JSON.parse( JSON.stringify(this.formData) )

Type 2: Parsing syntax of ES6

this.submitForm = { ...this.formData }


Related articles: