How can I call method in other component on vue.js 2?
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. The event will be globally available, due to $root
.
N.B. adding the vue instance to global window object is a bad practice
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.