about the use of $set and $delete in vue2

use of this.$set

when i usually use vue for development, i often encounter a problem like this:

that is, when the data contains a declared and assigned object or an array (array package object), we want to add a new property to the current object and update it, only to find that the view is not updated, only printed in the console

<template>
  <div>
      <span>{{obj}}</span>
      <input type="button" @click="add()">
  </div>
</template>

<script>
export default {
    data(){
        return{
            obj:{
                name:"Jack"
            }
        }
    },
    methods:{
        add(){
            if(!this.obj.age){
                this.obj.age = 20
            }else{
                this.obj.age++
            }
        }
    }
}
</script>

<style>
</style>

Limited by ES5, Vue .js cannot detect the addition or removal of object properties. Because Vue .js converts the property to getter/setter when the instance is initialized, the property must be on the data object for Vue to .js transform it to be responsive.

so the object registered in data is responsive, and the property added later is not responsive, just a normal property, in order to avoid the problem above, we use this.$set to add a new property of the responsiveness to the responsive object

grammar:this.$set(target,key,value)

target:target object (the one object/array to change)

key:Concrete property to change (new property)

value:The value of the new property (or reassigned value)

<template>
  <div>
      <span>{{obj}}</span>
      <input type="button" @click="add()">
  </div>
</template>

<script>
export default {
    data(){
        return{
            obj:{
                name:"Jack"
            }
        }
    },
    methods:{
        add(){
            if(!this.obj.age){
            	// grammar:
                this.$set(this.obj,"age",23)
            }else{
                this.obj.age++
            }
        }
    }
}
</script>

<style>
</style>

this.$delete

<template>
<div>
     {{testData.name}}
     <button @click="del">Delete</button>
</div>
</template>
<script>
export default {
  name: "Home",
  data () {
    return {
        testData:{
            name:"Jack"
        }
    };
  },
  methods:{
      del(){
          this.$delete(this.testData,"name")
      }
  }
}
</script>

Leave a Reply