How to call a method from outside the App object in Vue.js 3?

Viewed 1599

In Vue.js 2, I used to be able to do this call my initialize() method from outside my class like this:

<!DOCTYPE html>
<head>
    <script src="https://unpkg.com/vue@next"></script>
    <title>test</title>
</head>
<body>
    <div id="app">
        <div>{{message}}</div>
    </div>

    <script>
        const app = Vue.createApp({
            data() {
                return {
                    message: 'initial value'
                }
            },
            methods: {
                initialize() {
                    this.message = 'changed value';
                }
            }
        });
        app.mount("#app");
        app.initialize();
    </script>
</body>
</html>

But the above code in Vue.js 3 gets the error:

Uncaught TypeError: app.initialize is not a function

How can I do this in Vue.js 3?

1 Answers

You need to call the method on the component instance rather than the application instance:

const app = Vue.createApp({
  methods: {
    initialize() { /* ... */ }
  }
});

const vm = app.mount("#app");
vm.initialize();

The object passed to createApp contains the options for the root component. The mount method returns the root component instance.

There's an example of this in the documentation:

https://v3.vuejs.org/guide/data-methods.html#methods

You may also want to take a look at the following page, which explains the difference between the application instance and the root component instance.

https://v3.vuejs.org/guide/instance.html

Related