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

Detailed explanation of webpack-dev-server core concepts and cases

webpack-dev-server core concepts Webpack's Co...

Steps to change mysql character set to UTF8 under Linux system

Table of contents 1. Check the MySQL status in th...

A brief introduction to MySQL InnoDB ReplicaSet

Table of contents 01 Introduction to InnoDB Repli...

Understanding the CSS transform-origin property

Preface I recently made a fireworks animation, wh...

How to add a paging navigation bar to the page through Element UI

need Add a paging bar, which can jump to the page...

Gallery function implemented by native Js

Table of contents The first The second Native Js ...

Do you know how to use Vue to take screenshots of web pages?

Table of contents 1. Install html2Canvas 2. Intro...

Use of Vue filters and custom instructions

Table of contents Filters 01.What is 02. How to d...

Linux nohup command principle and example analysis

nohup Command When using Unix/Linux, we usually w...

Share 5 JS high-order functions

Table of contents 1. Introduction 2. Recursion 3....

Native JS to achieve cool paging effect

This article uses an example to share with you a ...

Nginx access control and parameter tuning methods

Nginx global variables There are many global vari...

JS achieves five-star praise case

This article shares the specific code of JS to ac...

Analysis of the Poor Performance Caused by Large Offset of LIMIT in MySQL Query

Preface We all know that MySQL query uses the sel...