How to call a custom Vue 3 method from outside vue app in JavaScript?

Viewed 2499

I have a simple app written in Vue. What I want is just to call a method from Vue, a custom method, outside of the Vue.createApp() method.

My code:

const app = Vue.createApp({
data() {
    return {
        data: ["this","is","an", "example"],
    }
 },
 methods: {
  getData() {
    return this.data;
  },
 },
});


app.mount('#app');

// This instruction fails!
console.log(app.getData());

When I am trying to execute the method on the last line, i get in the console:

Uncaught TypeError: Cannot read property 'content' of undefined

Why I can not execute the method? what is wrong?

2 Answers

For the specific question:

Why I can not execute the method?

The reason is because you're calling the method on the application instance, not the component where the function is defined. The first parameter to createApp is the root component.

To get hold of the root component, use:

const app = Vue.createApp({ /* root component's data, methods, etc */ });
const root = app.mount("#app");

// component methods accessible on return value from mount()
console.log(root.getData());

The code you've posted does in fact work.

/* only the style has been changed */

const { createApp } = Vue;

const app = createApp({
    template: '<div />',

    data: () => ({
        data: ['this', 'is', 'an', 'example'],
    }),

    methods: {
        getData() {
            return this.data;
        },
    },
}).mount('#app');

console.log(app.getData());

Edit

This is an anti-pattern and should generally be avoided. If you're looking to share state between distant components you should take a look at Vuex. If the components are close together, i.e. parent and child, look into props.

Could you provide more information on the motivation behind this?

Related