【问题标题】:How to make component watch for router if it is outside router-view?如果它在路由器视图之外,如何让组件监视路由器?
【发布时间】:2020-01-19 03:49:33
【问题描述】:

当路由器更改 url 时,我无法使 v-if for element 从函数中获取布尔值。

这是我的组件标题代码

<template>
    <header class="wfm-header">
        <div class="wfm-header__navigations">
            <div class="wfm-header__logo"></div>
        </div>
        <div
                v-if="isPlan"
                class="wfm-header-plan"
        >
            <div
                    class="wfm-header-plan__calendar"
                    v-if="isAuth || shopName">
                <wfm-calendar />
            </div>
        </div>
    </header>
</template>

<script lang="ts">
    @Component({
        components: {
            wfmCalendar,
        }
    })
    export default class wfmHeader extends Vue {
        ...
        get isPlan() {
            return this.$router.currentRoute.name === RouteNames.PLAN // it works only after Reload page
        }
        @Watch('$router.currentRoute.path')
        changeRouter() {
            console.log('plzChange') // it doesnt work
        }
    }
</script>

当我的路线发生变化时,我想更改 isPlan 值。我尝试使用 watch fo this.$router 并使用 beforeRouteUpdate 它没有帮助,我该怎么办?

【问题讨论】:

    标签: typescript vue.js vue-router


    【解决方案1】:

    你可以试试 在组件中的 $route 上设置一个观察者,如下所示:

    watch:{
        $route (to, from){
            // react to route changes
        }
    } 
    

    或者如果您需要打字稿,请检查此问题:

    Watch route changes in Vue.js with Typescript

    【讨论】:

    • 谢谢你,它有效!我忘了为手表添加{立即:真实,深度:真实}
    猜你喜欢
    • 2020-01-21
    • 2023-03-22
    • 2018-05-08
    • 1970-01-01
    • 2018-10-31
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多