【问题标题】:Vue.js Vuex action do not see getter from other moduleVue.js Vuex 动作看不到来自其他模块的 getter
【发布时间】:2020-11-27 18:29:18
【问题描述】:

我正在尝试使用来自其他模块的 getter 将 JWT 令牌获取到我的 http 查询中,如下所示:

 ...
    },
    actions: {
        async refreshContactData( state, getters, rootState, rootGetters ) {

            
            
            
            return axios.get('/test', {
                headers: {
                    Authorization: 'Bearer ' + rootGetters['user/getJWT']//the token is a variable which holds the token
                }
              }).then(response => {
                console.log(response)
            })
        }
    },
}

我的第二个模块如下所示:

//user.js

import axios from "axios"


export default {
    state: {
        jwt: 'asdfasdf',

    },
    getters: {
        getJWT: (state) => {
            console.log("WTF")
            return state.jwt;
          }

    },
    ...

它与主 index.js 存储文件相关联:

 //index.js
    
   ...
      modules: {
        user: User,
        contact: Contact
      },
   ...

我尝试了不同的配置,但我仍然在控制台中收到“未定义”错误:

vue.runtime.esm.js?2b0e:1888 TypeError: Cannot read property 'user/getJWT' of undefined
    at _callee$ (contact.js?7526:54)
    at tryCatch (runtime.js?96cf:63)
    at Generator.invoke [as _invoke] (runtime.js?96cf:293)
    at Generator.eval [as next] (runtime.js?96cf:118)
    at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
    at _next (asyncToGenerator.js?1da1:25)
    at eval (asyncToGenerator.js?1da1:32)
    at new Promise (<anonymous>)
    at eval (asyncToGenerator.js?1da1:21)
    at Store.refreshContactData (contact.js?7526:47)

我做错了什么?

【问题讨论】:

    标签: vue.js vuejs2 axios jwt vuex


    【解决方案1】:

    动作不像 getter 那样有多个参数。它们有一个上下文参数和一个有效负载参数。要获取rootGetters,您可以解构上下文参数:

    async refreshContactData({ rootGetters }) { // notice the braces
    ...
    }
    

    然后将定义rootGetters

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2020-07-20
      • 2023-04-09
      • 2018-06-03
      • 2019-09-04
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多