typescript - Vuex + Typescript:突变对象有效载荷始终未定义
问题描述
在运行时,我作为辅助参数传递给我的 Vuex 变异方法的对象有效负载始终是undefined
. 我的 Vuex 和组件文件都是用 TypeScript 编写的。
我index.ts
的 Vuex 商店文件如下所示(请注意,我使用的是模块化商店方法):
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()
回调有一个 type 的参数,AxiosResponse
它将实际响应包装在其data
属性中。代码应如下所示:
import axios, { AxiosResponse } from 'axios'
axios.get(/*...*/)
.then((response: AxiosResponse) => {
const profileResponse = response.data
store.commit('setProfile', profileResponse)
})
推荐阅读
- php - 如何在循环中的if条件中禁用表单按钮
- react-native - 排毒 - 从头到尾录制一个视频
- html - 如何使 svg pic 垂直和水平缩放
- mysql - 如何使用三个表在 MySQL 中使用 SQL 语句获取矩阵样式数据
- javascript - 如何使用本地存储中存储的颜色值?
- node.js - MongoDB中大型集合的聚合性能
- ios - UICollectionView 下方的按钮无法根据(Swift)内内容大小的约束正确定位
- java - Kubernetes部署微服务服务间通信的连接超时问题
- javascript - 用 Pako 放气,用 asp net core 充气
- laravel - 如何在 Lumen 中创建第二次迁移