6

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 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.