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

时间:2019-04-11 20:00:24

标签: vue.js vue-router

我正在尝试根据您首次直接访问Web应用程序的URL,将类nav-active设置为正确的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
                }

        }
    }
}

activenavItems布尔值的状态确定导航元素是否应具有nav-active类。我正在尝试通过以下方式使用当前路由来确定active是对还是假:

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

例如,有一次我直接从以下位置进入该信息中心:http://localhost:8000/account this.$route的项目全部为空,路径始终为/

非常感谢您的帮助, 谢谢

1 个答案:

答案 0 :(得分:1)

默认情况下,您不会使用这种方法跟踪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
                }
            ]
        }
    }
}
相关问题