问题描述
在运行时,我作为辅助参数传递给我的 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>
我做错了什么?
解决方法
axios.get().then()
回调有一个 AxiosResponse
类型的参数,它将实际响应包装在其 data
属性中。代码应如下所示:
import axios,{ AxiosResponse } from 'axios'
axios.get(/*...*/)
.then((response: AxiosResponse) => {
const profileResponse = response.data
store.commit('setProfile',profileResponse)
})