【问题标题】:How to get a route param如何获取路由参数
【发布时间】:2016-12-13 18:04:53
【问题描述】:

这是我的路由器的样子:

export default new VueRouter({
    mode: 'history',
    routes: [

        /**
         * Authentication
         */

        {   name: 'login',
            path: '/',
            component: Login,
            guest: true
        },

        {   name: 'registration',
            path: '/registreer',
            component: Registration,
            guest: true
        },

        /**
         * Forum
         */

        {   name: 'forum',
            path: '/forum',
            component: Forum,
            auth: true
        },
    ]
});

现在我想在转到/forum 时获得auth 的值。我如何获得该值?我在the docs 中找不到任何内容。

已经试过了:

router.beforeEach((to, from, next) => {
    console.log(to.auth);
    next()
});

但是什么都没有出现,只有undefined

有什么想法吗?

【问题讨论】:

  • 你需要遍历matched routes
  • 你不能像你想要的那样设置密钥.. 使用 meta : {auth:true}

标签: vue.js vue-router


【解决方案1】:

这是 Vuex 的一个很好的用例 - https://vuex.vuejs.org/en/intro.html

Vuex 允许您维护应用程序的状态,还可以存储各种 API 响应,这样您就不必在其他组件中重新加载相同的数据。

在您的特定情况下,如果auth 可用,您的forum 组件可以检查Vuex 状态(这可以在createdmounted 处理程序中完成)。如果auth 不可用,则应立即使用this.$router.replace("/login") 重新路由到身份验证页面

在您的auth 组件或login 组件中,您可以正常进行身份验证。用户登录成功后,您可以将服务器响应存储在 this.$store.state["auth"] - Vuex 状态,可全局用于所有组件。这可以按如下方式完成(作为 Vuex 商店中的一个突变):

Vue.set(state, "auth", currentUserDetailsObject)

之后,您可以重定向到forum组件,其中auththis.$store.state中可用,因此论坛可以继续正常显示该组件。

您可能需要一些时间来适应 actionsmutations 的概念,但是一旦您习惯了它,您会发现它对您的应用程序的其余部分非常有帮助。

【讨论】:

    【解决方案2】:
    • 我想你可以找到你想要的here
    • 您可能想了解Vuex
    • 那你就可以这样写代码了。

      if (!store.getters.auth) {
          next({
              path: '/login',
              query: {redirect: to.fullPath}
          })
      }
      

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 2013-04-30
      • 2021-09-18
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      相关资源
      最近更新 更多