JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > Vue >

The difference between Vue.set and this.$set in Vue

Author:JIYIK Last Updated:2025/02/28 Views:

In Vue, when we need to dynamically add or modify an item in an object or array, we usually use the Vue.setor this.$setmethod. Although these two methods have the same function, their usage and internal implementation are different.


View.set

Vue.setIt is a global method provided by Vue.js and can be used anywhere. It is used as follows:

Vue.set(target, key, value)

Among them, target represents the object or array to be added or modified, key represents the attribute name or index value to be added or modified, and value represents the attribute value to be added or modified.

For example, we have a data object:

data: {
  list: ['a', 'b', 'c']
}

If we want to listchange the first element of the array to 'd', we can use Vue.setthe method:

Vue.set(this.data.list, 0, 'd')

This will change the first element of the list array to 'd'.

It is important to note that Vue.setmethods can only be used on objects or arrays, not on basic data types (such as strings, numbers, Boolean values, etc.).


this.$set

this.$setIt is a method provided by the Vue instance and can only be used in the Vue instance. It is used as follows:

this.$set(target, key, value)

The meanings of target and key Vue.setare the same as those of the method, and value indicates the attribute value to be added or modified.

For example, we have a component:

export default {
  data() {
    return {
      list: ['a', 'b', 'c']
    }
  },
  methods: {
    changeList() {
      this.$set(this.list, 0, 'd')
    }
  }
}

If we want to listchange the first element of the array to 'd', we can use this.$setthe method.

It is important to note that this.$setmethods can only be used on objects or arrays, not on basic data types (such as strings, numbers, Boolean values, etc.).


The difference between Vue.set and this.$set

Vue.setand this.$sethave the same function, both can be used to dynamically add or modify an item in an object or array. However, their usage and internal implementation are different.

1. Usage

Vue.setIt is a global method that can be used anywhere; this.$setit is a method provided by the Vue instance and can only be used in the Vue instance.

2. Internal Implementation

Vue.setthis.$setThe internal implementation of and is slightly different. Vue.setThe method is implemented as follows:

Vue.set = function(obj, key, val) {
  if (Array.isArray(obj) && isValidArrayIndex(key)) {
    obj.length = Math.max(obj.length, key)
    obj.splice(key, 1, val)
    return val
  }
  if (hasOwn(obj, key)) {
    obj[key] = val
    return val
  }
  const ob = obj.__ob__
  if (!ob) {
    obj[key] = val
    return val
  }
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

this.$setThe implementation of the method is as follows :

export 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
}

As you can see, this.$setthe method has some more boundary checks and warning prompts in its implementation to increase the robustness and readability of the code.


Precautions

When using the Vue.setor this.$setmethod, please note the following points:

  1. Can only be used for objects or arrays, not for basic data types (such as strings, numbers, Boolean values, etc.).
  2. When modifying an item in an array, you need to ensure that the index value is within the legal range, otherwise an exception will be thrown.
  3. When using the this.$set method, you need to ensure that the method is used in the Vue instance, otherwise an exception will be thrown.
  4. When using the Vue.set or this.$set method, you need to make sure that the target object has been observed by the Vue instance, otherwise responsive updates cannot be achieved. If the target object is not observed, you can use the Vue.observable method to convert it to a responsive object.
  5. When using Vue.set or this.$set methods, you need to pay attention to performance issues. Since these two methods trigger Vue's responsive update mechanism, frequent modifications to objects or arrays may cause performance bottlenecks. To avoid this, you can try to use batch updates or asynchronous updates, or use native JavaScript methods to make modifications when responsive updates are not required.

Summarize

Vue.setand this.$setare methods used in Vue to dynamically add or modify an item in an object or array. They have the same function, but are used and implemented differently. When using these two methods, you need to pay attention to the target object being observed by the Vue instance, do not use them on basic data types, modify the index of the array to ensure that it is within the legal range, and pay attention to performance issues. Only by using these two methods correctly can you give full play to the advantages of Vue's responsive update mechanism and improve development efficiency and code quality.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Configuring Apache Web Server on Ubuntu and Debian

Publish Date:2025/04/05 Views:176 Category:OPERATING SYSTEM

This article shows you how to install Apache web server on Ubuntu and Debian, set it up, and access the access logs. Apache Web Server in Ubuntu and Debian Apache HTTP Server is a free and open source web server that is very popular. More t

The difference between Fork and Branch on GitHub

Publish Date:2025/04/03 Views:157 Category:Git

This article discusses the difference between Form and Branch on GitHub. In the context of coding, the current era relies more on collaboration. GitHub is one of the most commonly used collaboration tools. Forking and branching on GitHub ar

The difference between Git Push Origin and Git Push Origin Master

Publish Date:2025/03/29 Views:165 Category:Git

This article outlines the difference between the git push origin and commands. We use these commands to push changes to a remote repository. git push origin master The difference lies in how and when to use them, as explained below. We will

The difference between Git pull and Git clone

Publish Date:2025/03/26 Views:193 Category:Git

This tutorial will discuss the difference between the git clone and commands. git pull git pull Using commands in Git We use git pull the command to get updates from the remote to the local. This command will update the files in the local r

How to use Docker to image a Node.js web application

Publish Date:2025/03/26 Views:107 Category:Docker

Docker is a containerization platform that simplifies the packaging and execution of applications. Containers run as independent processes with their own file systems, but share the kernel of their host machine. Docker has attracted much at

The difference between CMD and ENTRYPOINT in Docker

Publish Date:2025/03/25 Views:142 Category:Docker

Docker containers have become the standard when it comes to managing software and dependencies in different environments. When working with real-world applications, you need to create a docker file before building your application container

The difference between Docker containers and Docker images

Publish Date:2025/03/25 Views:80 Category:Docker

In this article, we will understand the difference between containers and images by showing the components that make up containers and images and the features that make them different. Understanding Docker layers To create a custom image, w

My understanding of webservice is this

Publish Date:2025/03/18 Views:150 Category:NETWORK

Recently, I encountered such a project at work (temporarily named Project A). Project A itself was developed in PHP, but its data came from another project developed in Java (temporarily named Project B). Project A could not operate the dat

Which technology do you choose to implement the web chat room?

Publish Date:2025/03/18 Views:62 Category:NETWORK

With the rise of HTML5 Websockets, web chat applications are becoming more and more popular. Recently, I am working on a mobile web application, the core function of which is to implement web chat on the mobile phone. Of course, the functio

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial