this.$set() of vue

In the process of project development using vue, we may encounter a situation: when a vue instance is generated, when the data is assigned again, sometimes it will not be automatically updated to the view.

This is because when an object or array (the value in the array is an object) is declared or assigned in the data in Vue, a new attribute is added to the object. If the value of this attribute is updated, the view will not be updated.

The following code adds the age attribute to the person object:

data () {
    
    
  return {
    
    
    person: {
    
    
      name: '小明',
      gender: '男'
    }
  }
}
// mounted钩子函数,在实例挂载之后调用,一般用于页面初始化
mounted () {
    
    
  this.person.age = 18
}

When we want to render the age attribute value on the page, it cannot be used. The reason is that due to ES5 limitations, Vue.js cannot detect the addition or deletion of object attributes. Because Vue.js converts the property to getter/setter when initializing the instance, and the property must be on the data object in order for Vue.js to convert it and make it responsive, so it needs to be used at this time this.$set.

The correct wording should be:

mounted () {
    
    
  this.$set(this.person, "age", 18)
}

Simply talk about the three parameters of this.$set(target, “key”, “value”):
① The target object to be changed (it can also be an array)

② The attribute in the object to be changed (or the index of an element in the array)

③ Re-assigned value

Guess you like

Origin blog.csdn.net/qq_45846359/article/details/113185491