【问题标题】:$router.push doesn't respect route meta fields$router.push 不尊重路由元字段
【发布时间】:2017-08-01 04:03:39
【问题描述】:

当像这样使用$router.push 时:

this.$router.push({name: 'Home'})

...似乎我的路线元字段没有被识别。这是我的路线元字段以及我如何称呼它们:

路由元字段

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.user.authenticated) {
      next({
        path: '/login'
      })
    } else {
      next()
    }
  } else {
    next() // make sure to always call next()!
  }
})
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.preventAdmin)) {
    // this route shouldn't be available for admin, check role
    // if so, redirect to admin area.
    if (auth.user.role === '1') {
      next({
        path: '/admin/users'
      })
    } else {
      next()
    }
  } else {
    next() // make sure to always call next()!
  }
})

路线

routes: [
  {
   path: '/',
   name: 'Home',
   component: Home,
   meta: { requiresAuth: true, preventAdmin: true }
  },
]

如果我在特定路线上刷新,它们会按预期工作。

在使用$router.push 时,我是否必须做一些事情来确保我的路由元字段正常工作?

【问题讨论】:

    标签: vue.js vuejs2 vue-router


    【解决方案1】:

    您可以这样构建您的路由器视图:

    <router-view :key="$route.path"></router-view>
    

    在页面路由上达到与页面刷新相同的结果(至少对于您的路由器视图的内容)。我希望这样做可以解决问题,但如果没有,请告诉我。

    【讨论】:

    • 我使用this.$router.push({name: 'Home'}) 作为登录方法的一部分,所以&lt;router-view :key="$route.path"&gt;&lt;/router-view&gt; 不可用。
    • 这并不意味着它不可用,对吧?每当您导航到不同的页面时,都会触发路由器视图的关键参数,包括this.$router.push({ })
    猜你喜欢
    • 2021-08-02
    • 2020-02-19
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2011-11-13
    • 2018-04-03
    相关资源
    最近更新 更多