preface

Due to JavaScript limitations, Vue cannot detect array and object changes. However, there are ways to circumvent these limitations and ensure their responsiveness.

scenario

  1. When element UI TAB + Table is used together, the table data is updated, but the page view is not updated.
  2. Vue does not listen for its setter and getter methods, so it cannot implement bidirectional binding.

For the object

Vue cannot detect the addition or removal of property. Since Vue performs getter/setter conversions on property when it initializes the instance, the property must exist on the data object for Vue to convert it to reactive. Such as:

Var vm = new Vue({data:{a:1}}) // 'vm.a' is responsive vm.b = 2 // 'vm.b' is non-responsiveCopy the code

Vue does not allow dynamic root-level responsive properties to be added to already created instances. However, you can add responsive properties to nested objects using the vue.set (Object, propertyName, value) method. For example, for:

Vue.set(vm.someObject, 'b', 2)

You can also use the vm.$set instance method, which is also an alias for the global vue.set method:

this.$set(this.someObject,'b',2)

Sometimes you may need to assign multiple new properties to existing objects, such as object.assign () or _.extend(). However, new properties that are thus added to the object do not trigger updates. In this case, you should create a new object with the property of the original object and the property of the object to be mixed in.

// Replace 'object.assign (this.someObject, {a: 1, b: 2})' this.someObject = object.assign ({}, this.someobject, {a: 1, b: 2}) 'this.someobject = object.assign ({}, this.someobject, {a: 1, b: 2}) 2})Copy the code

For an array of

Vue cannot detect changes to the following arrays:

When you set an array item directly using an index, for example:

vm.items[indexOfItem] = newValue

When you modify the length of an array, for example:

vm.items.length = newLength

Here’s an example:

Var vm = new Vue({data: {items: ['a', 'b', 'c']}}) vm.items[1] = 'x' // not responsive vm.items. Length = 2 // Not responsiveCopy the code

To solve the first type of problem, the following two methods can achieve the same effect as vm.items[indexOfItem] = newValue, and also trigger status updates within a responsive system:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
Copy the code

You can also use the vm.$set instance method, which is an alias for the global method vue. set:

vm.$set(vm.items, indexOfItem, newValue)

To solve the second type of problem, you can use vm.items.splice(newLength)

Source: official documentation, CSDN