1. Overview
In this article, we will discuss the alternative solution to vue.set in Vue js 3. To learn more about Vue, refer to these articles.
2. Vue.set API in vue js
The Vue.set API adds a new property to an existing reactive object and triggers view updates.
This global API delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. These APIs are primarily used to get around the limitation that Vue cannot detect property deletions or creations.
3. Alternative to Vue.set in Vue 3
Vue.delete
and Vue.set
global APIs are not required in Vue 3 anymore. With the new reactivity system using proxies, Vue can detect all changes to reactive data.
Vue.$set(this.object, property, value) or this.$set(this.object, property, value)
In Vue 3, you can directly assign the property to the object and the object would be still reactive. You can rewrite the above code as:
// vue 3 this.object[property] = value
Similarly, you can use JavaScript delete
operator to delete property from the reactive object. The delete
operator removes a property from an object. If the property’s value is an object and there are no more references to the object, the object held by that property is released automatically.
delete object.property delete object[property]
object
: The name of an object, or an expression evaluating an object.
property
: The property to delete.
It returns true
or false
as a result. For example, the below code does not work in Vue 3. If you execute, you would get the error "TypeError: Cannot read properties of undefined (reading 'delete')".
<script setup> import { createApp, reactive } from 'vue' const obj = reactive({ a: 1, b: 2, c: 3 }) </script> <template> <div id="app"> Object: {{ obj }} <hr> <template v-for="(item, key) in obj"> <button @click="Vue.delete(this.obj, key)">Delete key {{ key }}</button> <br> </template> <button @click="obj['z'] = 'Added'">Add key z</button> </div> </template>
By replacing Vue.delete
from the above code as delete obj[key]
will make it work in Vue 3.
<script setup> import { createApp, reactive } from 'vue' const obj = reactive({ a: 1, b: 2, c: 3 }) </script> <template> <div id="app"> Object: {{ obj }} <hr> <template v-for="(item, key) in obj"> <button @click="delete obj[key]">Delete key {{ key }}</button> <br> </template> <button @click="obj['z'] = 'Added'">Add key z</button> </div> </template>
3. Conclusion
To sum up, we have learned the alternative way to use Vue.set global API in the latest Vue js. Since Vue 3 uses a proxy in the new reactivity system, it can detect all changes to the object. So normal JavaScript delete operator or direct property assignment works fine in this case.