【问题标题】:Vuex + Typescript: Mutation Object Payloads are Always UndefinedVuex + Typescript:突变对象有效载荷始终未定义
【发布时间】:2021-03-31 15:53:04
【问题描述】:

在运行时,我作为辅助参数传递给我的 Vuex 变异方法的对象有效负载始终是 undefined。我的 Vuex 和组件文件都是用 TypeScript 编写的。

我的 Vuex 商店的 index.ts 文件如下所示(请注意,我使用的是模块化商店方法):

import Profile from '@/models/Profile'
import { createStore } from 'vuex'

const userModule = {
  state: () => ({
    profile: Profile
  }),
  mutations: {
    setProfile (state:any, profile: Profile) {
      // `state` is the local module state
      state.profile = profile //**RUNTIME ERROR: profile = undefined
    } 
  },
  getters: {
    getProfile (state:any) {
      return state.profile
    }
  }
}

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    user: userModule
  }
})

我从我的 Vue 组件的 methods 提交到商店,如下所示:

 <script lang="ts">
 export default Vue.extend({
    methods: {
      fetchProfile() {
        axios
            .get("/getUser", requestHeader)
            .then((profileResponse: Profile) => {
              //store profile in Vue Store
              store.commit('setProfile', profileResponse)
            })
      }
    }
 })
 </script>

我做错了什么?

【问题讨论】:

  • profileResponse 提交的时候肯定不是 undefined 吗?

标签: typescript vue.js vuex vuex-modules


【解决方案1】:

axios.get().then() 回调有一个AxiosResponse 类型的参数,它将实际响应包装在其data 属性中。代码应如下所示:

import axios, { AxiosResponse } from 'axios'

axios.get(/*...*/)
  .then((response: AxiosResponse) => {
    const profileResponse = response.data
    store.commit('setProfile', profileResponse)
  })

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 2018-08-17
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多