There may be occasions where you need to access and update the instance's data
.
In Vue JS 2, this task was simpler, but Vue JS 3 has increased its encapsulation. However, it is still possible to modify state from external sources. You can find more information about this here
If you are using Vue with build steps, which is common, your setup will look something like this:
const app = createApp({
data() {
return {}
},
})
.mount('#app');
If you try typing app
in the browser console, it will return null because of the scope limitation imposed by compiled .js
files.
However, if you attach app
to a global object like document
:
document.app = createApp({
data() {
return {}
},
})
.mount('#app');
Now when you type app
in the console, it will no longer be null
, but the actual Vue instance. This allows you to access and manipulate the instance's data
through the app.$data
property.
But what if the instance includes components
and you want to modify their $data
? In previous versions, you could access children using the $children
property. Now, you need to assign a ref
to each component and then access them by their ref name. For example:
app.$refs.alertComponent.$data.message = "New message!"