首页 > 解决方案 > vuejs 路由器 - this.$route 在刷新时始终为空

问题描述

我正在尝试nav-active根据您第一次直接访问 webapp 的 url 将类设置为正确的 nav 元素。

我有几条路线:

export default new Router({
mode: 'history',
routes: [
    {
    path: '/',
    name: 'home',
    component: () => import('./views/Home.vue')
    },
    {
    path: '/account',
    name: 'account',
    component: () => import('./views/Account.vue')
    }
    ]
});

这是我的导航栏组件(NavBar):

export default {
    name: 'NavBar',
    components: {
        NavLogo,
        NavItem
    },
    data() {
        return {
            navItems: [
                {           /* root navigation */
                    id: 0,
                    type: 'root',
                    name: 'home',
                    route: '/',
                    active: this.$route.name === 'home' }, 
                {
                    id: 1,
                    type: 'root',
                    name: 'account',
                    route: '/account',
                    active: false
                }

        }
    }
}

active内部布尔值的状态navItems决定了导航元素是否应该具有nav-active类。我正在尝试使用当前路由来确定active应该是真还是假,通过这种方式使用它:

active: this.$route.name === 'account'

但是,例如,我直接从以下位置进入此仪表板:http://localhost:8000/account this.$route的项目都是空的,路径始终是/

非常感谢帮助,谢谢

标签: vue.jsvue-router

解决方案


默认情况下,您不会this.$route.name使用这种方法跟踪更改。尝试创建一个解析为 的计算属性this.$route.name,并在您的数据属性声明中使用它。实际上,您可以将整个内容粘贴到计算属性中,因为您不太可能更改它。

export default {
    name: 'NavBar',
    components: {
        NavLogo,
        NavItem
    },
    computed: {
        routeName(){
           return this.$route.name
        },
        navItems(){
            return [
                {           /* root navigation */
                    id: 0,
                    type: 'root',
                    name: 'home',
                    route: '/',
                    active: this.routeName === 'home' }, 
                {
                    id: 1,
                    type: 'root',
                    name: 'account',
                    route: '/account',
                    active: false
                }
            ]
        }
    }
}

推荐阅读