const app = createApp({
data() {
return {
some_id: 0
}
}
})
I have an autocomplete on a field. When a label is selected, I want to pass the id to a Vue app.
onSelectItem: ({label, value}) => {
app.some_id = value;
}
This worked in an old v2 version of Vue.js. Now, I can't even call the methods of the Vue app from other JavaScript functions. What is the best solution?
CodePudding user response:
There are certain circumstances where you may need to access and mutate, change the instance's data
.
This was easier in Vue JS 2, but Vue JS 3 has become more encapsulated. However it does not mean mutating state from outside is impossible. You can read about it here
Supposing that you are using Vue with build steps, which covers most cases, you will have something like this:
const app = createApp({
data() {
return {}
},
})
.mount('#app');
Now if you head to browser console and type app
, it will be null because it is limited to the scope of compiled .js
files.
But if you attach app
to a global object, document
for example:
document.app = createApp({
data() {
return {}
},
})
.mount('#app');
Now if you type app
in the console, it will no longer be null
, but the Vue instance. From there, you can access the instance's data
as well as mutate it via app.$data
property.
Now what if the instance has components
and you want to mutate their $data
? In previous versions, it was possible to access children via $children
property. But now in order to access children, you have to give each of them a ref
, then access via their ref name. For example:
app.$refs.alertComponent.$data.message = "New message!"