First, the official document:

vm.$set( target, propertyName/index, value )

  • Parameters:

  • {Object | Array} target

  • {string | number} propertyName/index

  • {any} value

  • Return value: the value set.

  • Usage:

This is the alias for global vue.set.

  • Reference: the Vue. Set

Set method is to give a simple goal (Object | Array), a new attribute Here is a piece of code

let array=[];
vm.$set(array,0.'newVal')
/ / the result [' newVal];
Copy the code

This and

let array=[];
array[0] ='newVal';
/ / the result [' newVal];
Copy the code

Exactly the same in form. What’s the difference? Now, in the form of a small project, I’ll tell you what set does. Template section

 <div id="app">
    <button @click="change">change</button>
     {{arrayVal}}  -- {{objVal}}
  </div>
Copy the code

Javascript part

export default {
  name: "App".data: function() {
    return {
      arrayVal: [].objVal:{}
    };
  },
  methods: {
    change() {
      this.arrayVal[0] ="New content"
      this.objVal['newItem'] ='New content'
      // this.$set(this. ArrayVal,0,' new content ')
      // this.$set(this.objVal,'item',' new content ')}},components: {}};Copy the code

Page Interface

When you click change, the interface doesn’t change at all, but when you look at the console, the data is actually filled in.

Is this Vue’s pot? In ES5, the Object. Observe method has been abandoned. Vue cannot listen for Object property deletion or addition, so using deep to listen for Object prop is useless. Open the annotation

 methods: {
    change() {
      // this.arrayVal[0]=" New content"
      // this.objVal['newItem']=' new content '
      this.$set(this.arrayVal,0.'New content')
      this.$set(this.objVal,'item'.'New content')}},Copy the code

Click again on theThe data is rendered correctly to the interface.

Summary: the vm.$set method can make objects and arrays unlistener to listener, and render data properly.