Vuex / Vue-Router-将auth:user ID从vuex存储传递到vue-router路由器链接参数

时间:2020-01-15 04:09:05

标签: vue.js vuex vue-router

是否可以将当前登录的用户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>

1 个答案:

答案 0 :(得分:1)

问题似乎出在访问存储中,因为默认情况下,this.$store被注入到组件中,因此您可以在模板中使用$store,然后模板应该是:

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

但是,在访问存储状态值时,建议的方法是使用vuex的mapState Helper

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

,因此您可以按以下方式使用它:

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