【问题标题】:vuejs router - this.$route is always empty on refreshvuejs 路由器 - this.$route 在刷新时始终为空
【发布时间】:2019-09-02 13:11:17
【问题描述】:

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

我有几条路线:

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
                }

        }
    }
}

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

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

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

非常感谢您的帮助, 谢谢

【问题讨论】:

    标签: vue.js vue-router


    【解决方案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
                    }
                ]
            }
        }
    }
    

    【讨论】:

    • 嗯,computed 和 created() 属性都没有返回正确的this.$route,你有什么例子吗?
    • 我编辑了答案!你在那里缺少一个右方括号
    猜你喜欢
    • 2018-07-05
    • 1970-01-01
    • 2021-08-07
    • 2019-12-02
    • 2022-07-20
    • 1970-01-01
    • 2018-02-04
    • 2018-02-15
    • 2018-05-26
    相关资源
    最近更新 更多