How can I call method in other component on vue.js 2?

和自甴很熟 提交于 2019-12-01 06:46:53

If these 2 components are siblings (no parent & child), then one solution is to use event bus.

General idea is to build a global event handler like so: in main.js

window.Event = new Vue();

Then in your first component fire an event:

....
.then((response) => {
     Event.$emit('createImage', item, response)
});

and in second component register a handler for listening to createImage event in mounted() hook:

...
mounted() {
    Event.$on('createImage', (item, response) => {
        // your code goes here
    }
}

You can find more info by reading this turtorial and watching this screen cast.

No two components don't have a parent/child relation. They are all connected through the root vue instance. To access the root vue instance just call this.$root and you get the root instance.

    ....
    .then((response) => {
        this.$root.$emit('createImage', item, response)
    });

and in the second component make the function that needs to be triggered

    ...
    mounted() {
        this.$root.$on('createImage', (item, response) => {
            // your code goes here
        }
    }

It acts more like a socket.

N.B. adding the vue instance to global window object is a bad practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!