skip to Main Content

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


  1. You can use $data to access or edit the message like :

     app.$data.message = "My name is Florian"; // Access the reactive data object using $data
    
    
    Login or Signup to reply.
  2. In Vue 3, you can access the app’s instance through the _instance property and fiddle around with it:

    app._instance.data.message = "Your name is Florian";
    

    Here it is in a snippet:

    const app = Vue.createApp({
      template: `<h1>{{ message }}</h1>`,
      data() {
        return {
          message: "Hello World!"
        }
      }
    })
    
    app.mount('#app');
    app._instance.data.message = "Your name is Florian";
    <div id="app"></div>
    
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    Login or Signup to reply.
  3. The problem is that application instance is accessed, while it’s root component instance that needs to be in this case.

    It should be:

    const vm = app.mount('#app');
    vm.message = "My name is Florian";
    

    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:

    const app = Vue.createApp({
      ...
      expose: ['setMessage'],
      methods: {
        setMessage(message) {
          this.message = message;
        }
      }
    });
    
    const vm = app.mount('#app');
    vm.setMessage("My name is Florian");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search