programing

Vue 라우터가 라우터 링크-정확한 활성에서 클릭 감지

prostudy 2022. 3. 20. 12:56
반응형

Vue 라우터가 라우터 링크-정확한 활성에서 클릭 감지

나는 이 질문을 여러 번 보았지만, 좋은 답변이 없었다.

링크가 있는 탑메뉴가 있으며 현재 있는 페이지의 링크를 클릭할 때 기능을 트리거하고 싶다.

이걸 어떻게 해?

구성 요소 내 가드는 경로가 변경되지 않으므로 트리거하지 않는다는 점을 기억하십시오.

당신은 모든 링크에서 함수를 트리거하고 파라미터를 통과한 안에서 항해를 트리거하고자 할 것이다.

그런 다음 현재 페이지 URL이 전달된 매개 변수와 일치하는지 확인하십시오.

예시

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

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

이것은 프로그램 탐색이라고 불리며 여기서 더 많이 볼 수 있다.

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

좀 더 우아한 해결책을 찾은 것 같아 링크 포장지를 만들었어

<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>

그럼 간단한 믹스인

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)
            }
        }
    }
}

나는 이것이 최적의 해결책이라고 믿는다.라우터 링크를 메뉴 링크로 바꾸기만 하면 된다.

참조URL: https://stackoverflow.com/questions/54620577/vue-router-detect-click-on-router-link-exact-active

반응형