Jimbo
Jimbo

Reputation: 81

Vue router-link and custom event

I'm trying to make a custom event on a router-link in vue and it doesn't seem to be working. I want to do something like this-

parent-

<Home @customEvent="myEventHandler" />

script-

export default {
methods: {
    myEventHandler() {
        console.log('yay')
    }
}

child

export default {
...
mounted() {
    axios.get('api/link').then(res => {
        this.posts = res.data;
        this.$emit('customEvent')
    }
}

This works fine to create the log of yay with a regular component but when I try to do something like this-

<router-link to='/home' @customEvent="myEventHandler">Home</router-link>

It doesn't seem to work. How do you listen for custom events from a component thats created using router-link?

Thanks in advance...

Upvotes: 1

Views: 1755

Answers (1)

ittus
ittus

Reputation: 22393

It's possible. You can only $emit event from children to parent, you can't $emit event between 2 different router

Emit event from children to parent

enter image description here

Can't emit event between 2 different routes:

enter image description here

To work around this, you can create a wrapper component for both component A and component B, then using router-view to receive event

Upvotes: 1

Related Questions