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

WeChat applet implements the Record function

This article shares the specific code for the WeC...

Learning to build React scaffolding

1. Complexity of front-end engineering If we are ...

Example of how to identify the user using a linux Bash script

It is often necessary to run commands with sudo i...

What to do if you forget your Linux/Mac MySQL password

What to do if you forget your Linux/Mac MySQL pas...

Example code and method of storing arrays in mysql

In many cases, arrays are often used when writing...

mysql group_concat method example to write group fields into one row

This article uses an example to describe how to u...

Two problems encountered when deploying rabbitmq with Docker

1. Background The following two problems are enco...

Example of how to quickly delete a 2T table in mysql in Innodb

Preface This article mainly introduces the releva...

jQuery manipulates cookies

Copy code The code is as follows: jQuery.cookie =...

About front-end JavaScript ES6 details

Table of contents 1. Introduction 1.1 Babel Trans...

Summary of MySQL password modification methods

Methods for changing passwords before MySQL 5.7: ...

Xftp download and installation tutorial (graphic tutorial)

If you want to transfer files between Windows and...

Analysis of MySQL concurrency issues and solutions

Table of contents 1. Background 2. Slow query cau...

How to implement controllable dotted line with CSS

Preface Using css to generate dotted lines is a p...