Vue.js 3.0 Tutorial
Vue.js 3.0 Component Advanced
Vue.js 3.0 Transitions & Animations
Vue.js 3.0 Reusable & Combinable
Vue.js 3.0 Advanced
Vue.js 3.0 Tools
Vue.js 3.0 Scale
Vue.js 3.0 Accessibility
Vue.js 3.0 Migrating from Vue2
Vue.js 3.0 Contribute Documentation
Vue.js 3.0 API References
Vue.js 3.0 Style Guide
Vue.js uses a reactivity system that helps it know when to update the DOM. However, Vue.js can only detect changes to properties that existed when the reactive object was created. This means that if you add a new property to the object after it's been created, Vue.js will not track it, and the view won't be updated when that property changes. This issue often surfaces when working with Vue's reactivity system, especially for new developers.
Example of the problem
<template> <div> <button @click="addProperty">Add Property</button> {{ myObject }} </div> </template> <script> export default { data() { return { myObject: {} } }, methods: { addProperty() { this.myObject.newProperty = 'Hello, Vue!' } } } </script>
In this example, when you click the button, the addProperty
method adds a new property to myObject
. However, because newProperty
wasn't present when myObject
was created, Vue.js won't track it, and the change won't be reflected in the view.
Solution
To solve this issue, Vue.js provides a global method Vue.set
(or this.$set
in a component context), that allows you to add a property to an object and make sure it's reactive:
<template> <div> <button @click="addProperty">Add Property</button> {{ myObject }} </div> </template> <script> export default { data() { return { myObject: {} } }, methods: { addProperty() { this.$set(this.myObject, 'newProperty', 'Hello, Vue!') } } } </script>
In this updated example, when you click the button, the addProperty
method adds a new property to myObject
using this.$set
. This way, the property is reactive, and the change is reflected in the view.
Note: Similar to adding new properties, Vue cannot detect property deletion. If you want to trigger view updates on property deletion, use Vue.delete(object, propertyName)
.
It's important to remember this aspect of Vue.js's reactivity system to avoid problems in your applications. It's recommended to declare all the properties you need in your data objects upfront, even with an initial value of null
or undefined
, so Vue can track them from the start.