I wonder how to change the property of a vue app from outside. So I want to create a new vue app called app and set app.propertyName = someValue, but as tried below, that doesn’t work. How could you achieve it?
<!DOCTYPE html>
<html>
<head>
<title>The template configuration option</title>
<style>
#app {
display: inline-block;
padding: 10px;
font-size: x-large;
background-color: lightgreen;
}
</style>
</head>
<body>
<h1>'template' Example</h1>
<p>All HTML code from inside the div tag with id="app" is moved inside the 'template' configuration option, in backtick quotes.</p>
<div id="app"></div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
template: `<h1>{{ message }}</h1>
<p>This is a second line of HTML code, inside backtick quotes</p>`,
data() {
return {
message: "Hello World!"
}
}
})
app.mount('#app');
app.message = "My name is Florian"; //This line of code doesn't work
</script>
</body>
</html>
3
Answers
You can use $data to access or edit the message like :
In Vue 3, you can access the app’s instance through the
_instance
property and fiddle around with it:Here it is in a snippet:
The problem is that application instance is accessed, while it’s root component instance that needs to be in this case.
It should be:
It’s a bad practice to modify private data from the outside as this breaks the encapsulation. If this is the intended behaviour, component public API should preferably be defined: