【问题标题】:Vuex / Vue-Router - Passing auth:user id from vuex store to vue-router router-link paramsVuex / Vue-Router - 将 auth:user id 从 vuex 存储传递到 vue-router 路由器链接参数
【发布时间】:2020-05-01 20:12:59
【问题描述】:

是否可以将当前登录用户的 id 传递给路由器链接的params

这是我当前的代码,我想在基于params id的页面中呈现信息

routes.js

  { 
    path: '/objective/employee/:id', 
    name: 'employee-objective', 
    component: () => import('@/views/EmployeeObjective'),
    meta: { requiresAuth: true }
  },

Component.vue

    created () {
      this.$store.dispatch('authUserInformation')
    },

    computed: {
      loggedIn () {
        return this.$store.getters.loggedIn
      },
      authUser () {
        return this.$store.state.authUser
      }
    }

路由器链接

<router-link :to="{ name: 'employee-objective', 
params: { 
  id: // this.$store.state.authUser <- does not work
      // authUser[0].id <- does not also work
}}">
Click Here
</router-link>

【问题讨论】:

  • 我认为问题出在你的路由器链接
  • &lt;router-link :to="{ name: 'employee-objective', params: { id: $store.state.authUser }}"&gt;

标签: vue.js vuex vue-router


【解决方案1】:

问题似乎在于访问商店,因为默认情况下,this.$store 被注入到组件中,因此您可以在模板中使用$store,那么应该是:

<router-link :to="{ name: 'employee-objective', params: { id: $store.state.authUser }}">

但是,在访问 store state 值时,推荐的方式是使用 vuex 的mapState Helper

computed: {
  ...mapState([
    // map this.authUser to store.state.authUser 
    'authUser '
  ])
}

所以你可以这样使用它:

<router-link :to="{ name: 'employee-objective', params: { id: authUser }}">

【讨论】:

  • 我尝试了您的两个建议,它都表明 $store / authUser 是未定义的,即使它已被声明。很奇怪。
  • 没关系,我能够让它工作,但它只是返回一个对象。
  • 啊啊啊啊!抱歉,没有注意到您正在使用箭头功能。试试data() { return { employees: this.$store.state.authUsers } }
  • 您可以了解更多关于普通函数和箭头函数here。别担心。请随意提问:D
  • 是的,有一种方法可以访问$store,但您将不得不这样做data: self =&gt; ({ employees: self.$store.state.authUsers })。哪个更好是您的选择。我选择常规功能 tho
猜你喜欢
  • 2018-10-02
  • 2021-05-03
  • 2016-08-10
  • 2019-09-09
  • 2023-03-06
  • 2017-07-25
  • 2021-01-20
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多