The difference between Vue.set and this.$set in Vue
In Vue, when we need to dynamically add or modify an item in an object or array, we usually use the Vue.set
or this.$set
method. Although these two methods have the same function, their usage and internal implementation are different.
View.set
Vue.set
It 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 list
change the first element of the array to 'd', we can use Vue.set
the 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.set
methods can only be used on objects or arrays, not on basic data types (such as strings, numbers, Boolean values, etc.).
this.$set
this.$set
It 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.set
are 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 list
change the first element of the array to 'd', we can use this.$set
the method.
It is important to note that
this.$set
methods 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.set
and this.$set
have 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.set
It is a global method that can be used anywhere; this.$set
it is a method provided by the Vue instance and can only be used in the Vue instance.
2. Internal Implementation
Vue.set
this.$set
The internal implementation of and is slightly different. Vue.set
The 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.$set
The 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.$set
the 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.set
or this.$set
method, please note the following points:
- Can only be used for objects or arrays, not for basic data types (such as strings, numbers, Boolean values, etc.).
- 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.
- 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.
- 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.
- 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.set
and this.$set
are 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.
Related Articles
Webpack packages ES6 and CommonJs mixed React
Publish Date:2025/03/02 Views:179 Category:React
-
This article mainly introduces how to use webpack to package and compile React mixed with ES6 and CommonJs. It is a process of upgrading the React environment.
Details that need to be paid attention to when compiling react with webpack
Publish Date:2025/03/02 Views:199 Category:React
-
It is very convenient to compile and package react using webpack. Both need to be installed using npm. However, if you do not pay attention to the installation location of webpack and react parser babel during use, problems will occur during
How to scroll to the top or bottom of the page in Vue.js
Publish Date:2025/03/01 Views:96 Category:Vue
-
Vue.js is a popular front-end framework that helps developers build efficient and maintainable applications. In Vue.js, scrolling the page to the top or bottom is a common requirement. In this article, we will introduce how to implement this
Display element or text on mouse hover in vue
Publish Date:2025/03/01 Views:179 Category:Vue
-
Vue.js is a popular JavaScript framework that makes web application development easier and more efficient. In this tutorial, we will learn how to use Vue.js to display an element or text on mouse hover. This tutorial will cover the following
When watching an object in Vue, how to exclude certain properties from being watc
Publish Date:2025/03/01 Views:125 Category:Vue
-
When using watch in Vue, you may need to monitor an object, but only care about certain properties in the object, not all properties of the object. In this case, you can use deep monitoring and calculated properties, or add some options to w
What is the use of the immediate property of watch in Vue?
Publish Date:2025/03/01 Views:67 Category:Vue
-
In Vue, watch is a way to perform asynchronous tasks or trigger responsive dependencies when data changes. In most cases, watch will be delayed by default. This means that the watch will only be triggered when the value being monitored chang
Setting up checkbox functionality in Vue
Publish Date:2025/03/01 Views:186 Category:Vue
-
In Vue, checkboxes are a very common interactive component that allows users to select multiple options. This article will introduce how to set up checkbox functionality in Vue and provide some practical examples.
What happens if a child component changes the data in props in Vue?
Publish Date:2025/03/01 Views:140 Category:Vue
-
In Vue, when a child component changes the data in props, it will cause the responsiveness of the parent component and other child components to change. First, you need to understand that props is a way to pass data from a parent component t
How to refresh the page in Vue
Publish Date:2025/03/01 Views:91 Category:Vue
-
Vue is a popular JavaScript framework that provides many convenient tools and methods for building web applications. In Vue, page updates are usually achieved through data binding and responsive systems. But sometimes you need to refresh the