John
John

Reputation: 1123

Vue router detect click on router-link-exact-active

I've seen this question multiple times, but without a good response

I have a topmenu with links and I want to trigger a function when I click the link of the page that I'm on right now

How do I achieve this?

Remember the in-component guards wont trigger because the route does not change

Upvotes: 0

Views: 2248

Answers (2)

John
John

Reputation: 1123

I believe I found a more elegant solution I made a wrapper for links

<template>
    <a :href="resolvedRoute.route.fullPath" :class="{ 'is-active': resolvedRoute.route.name == $route.name }" @click.prevent="clicked">
        <slot></slot>
    </a>
</template>

<script>
    import EventBus from '@/event-bus'

    export default {
        name: 'menu-link',
        props: {
            to: {
                type: Object,
                default: {}
            }
        },
        computed: {
            isExactActive(){
                return this.$route.fullPath == this.resolvedRoute.route.fullPath
            },
            resolvedRoute(){
                return this.$router.resolve(this.to)
            }
        },
        methods: {
            clicked(){
                if(this.isExactActive)
                    return EventBus.$emit('page-reload', this.resolvedRoute.route)

                this.$router.push(this.to)
            }
        }
    }
</script>

Then a simple mixin

import EventBus from '@/event-bus'

export default {
    mounted(){
        EventBus.$on('page-reload', this.checkPageReload)
    },
    beforeDestroy(){
        EventBus.$off('page-reload', this.checkPageReload)
    },
    methods: {
        checkPageReload(route){
            if(route.name == this.$options.name && this.pageReload){
                EventBus.$emit('page-loading', true)
                this.pageReload(route)
            }
        }
    }
}

I believe this is the optimal solution. I'll just have to replace router-link with menu-link

Upvotes: 1

Michael Mano
Michael Mano

Reputation: 3440

You would want to trigger a function on all links and trigger the navigate from in there passed by a param.

Then check if the current page URL matches the passed param.

E.g.

if (this.$router.currentRoute == 'param passed') {
    return someOtherFucntion();
}

return this.$router.push('param passed');

Its called programmatic navigation you can see more here.

https://router.vuejs.org/guide/essentials/navigation.html#programmatic-navigation

Upvotes: 1

Related Questions