vuejs 路由器 - this.$route 在刷新时始终为空

vuejs router - this.$route is always empty on refresh

我正在尝试将 class nav-active 设置为正确的导航元素,基于 url 您第一次直接访问 Web 应用程序的内容。

我有几条路线:

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
                }

        }
    }
}

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

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

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

非常感谢您的帮助, 谢谢

默认情况下,您不会使用此方法跟踪 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
                }
            ]
        }
    }
}