Vue.set() and this.$set() usage and difference

Vue.set() and this.$set() usage and difference

When we use Vue for development, we may encounter a situation: after generating a Vue instance, when assigning data again, sometimes it is not automatically updated to the view; when we look at the Vue document, we will find such a sentence: if you add new properties to the instance after the instance is created, it will not trigger a view update. The following code adds the age attribute to the student object

data () {
  return {
    student:
      name: '',
      sex: ''
    }
  }
}
mounted () { //——Hook function, after the instance is mounted this.student.age = 24
}

Due to the limitations of ES5, Vue.js cannot detect the addition or removal of object properties. Because Vue.js converts properties to getters/setters when initializing the instance, the property must be on the data object in order for Vue.js to convert it and make it responsive.

Correct way to write: this.$set(this.data,"key",value')

mounted () {
  this.$set(this.student,"age", 24)
}

:: Vue does not allow dynamically adding root-level responsive properties.

For example:

const app = new Vue({
  data: {
    a: 1
  }
  // render: h => h(Suduko)
}).$mount('#app1')

Vue.set(app.data, 'b', 2)

You can only use the Vue.set(object, propertyName, value) method to add responsive properties to nested objects, for example

var vm = new Vue({
    el:'#test',
    data:{
        //The info root attribute already exists in data:{
            name:'Xiaoming';
        }
    }
});
//Add a gender attribute to info Vue.set(vm.info,'sex','男');

Vue.set() and this.$set() implementation principle

Let's first look at the source code of Vue.set():

import { set } from '../observer/index'

...
Vue.set = set
...

Let's take a look at the source code of this.$set():

import { set } from '../observer/index'

...
Vue.prototype.$set = set
...

As a result, we found that the implementation principles of the two APIs, Vue.set() and this.$set(), are basically the same, both using the set function. The set function is exported from the ../observer/index file. The difference is that Vue.set() binds the set function to the Vue constructor, while this.$set() binds the set function to the Vue prototype.

function set (target: Array<any> | Object, key: any, val: any): any {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid adding reactive properties to a Vue instance or its root $data ' +
      'at runtime - declare it upfront in the data option.'
    )
    return val
  }
  if (!ob) {
    target[key] = val
    return val
  }
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

We found that the set function receives three parameters: target, key, and val, where the value of target is an array or object, which corresponds exactly to the parameters passed in when calling the Vue.set() method given by the official website.

refer to:

Pitfalls encountered in Vue --- Change detection issues (array related)

This concludes this article about the usage and differences of Vue.set() and this.$set(). For more related Vue.set() and this.$set() content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Parsing Vue.set() and this.$set() from vue source code
  • Vue.set() this.$set() triggers view updates and considerations
  • Introduction to the usage and scenarios of Vue.set and this.$set

<<:  A brief analysis of the problem of Mysql 8.0 version driving getTables to return all database tables

>>:  How to configure Linux to use LDAP user authentication

Recommend

How to select all child elements and add styles to them in CSS

method: Take less in the actual project as an exa...

Analysis of Mysql transaction characteristics and level principles

1. What is a transaction? A database transaction ...

Vue implements chat interface

This article example shares the specific code of ...

Detailed explanation of the use of Vue h function

Table of contents 1. Understanding 2. Use 1. h() ...

Installation, configuration and use of process daemon supervisor in Linux

Supervisor is a very good daemon management tool....

Object-Oriented Programming with XHTML and CSS

<br />If only XHTML and CSS were object-orie...

MySQL 8.0 New Features - Introduction to the Use of Management Port

Table of contents Preface Connection Management A...

Let you understand the deep copy of js

Table of contents js deep copy Data storage metho...

JavaScript to achieve fixed sidebar

Use javascript to implement a fixed sidebar, for ...

MySQL 8.0.12 installation steps and basic usage tutorial under Windows

This article shares the installation steps and us...

HTML+CSS+jQuery imitates the search hot list tab effect with screenshots

Copy code The code is as follows: <!DOCTYPE ht...

How to skip errors in mysql master-slave replication

1. Traditional binlog master-slave replication, s...

TypeScript uses vscode to monitor the code compilation process

Install Install ts command globally npm install -...

HTML multi-header table code

1. Multi-header table code Copy code The code is a...