使用Axios从伪API获取数据到Vuex Store未达预期效果
排查Vuex + Axios获取数据到Store的问题
我帮你梳理了代码里的问题,这几个错误是导致你无法得到预期结果的核心原因:
1. Commit方法的使用完全不符合规范
Vuex的commit方法第一个参数必须是mutation的名称字符串,第二个参数才是要传递给mutation的payload数据。你现在写的commit(self.posts=response.data)和commit(console.log(...))完全不对,根本触发不了正确的mutation逻辑。
2. Actions里的this指向错误
在Vuex的action函数中,this并不指向Vue实例或store,而且你已经通过解构拿到了commit方法,完全不需要var self = this这种写法——这只会让self.posts变成undefined,进一步引发错误。
3. Vuex构造函数的大小写错误
你写的是vuex.Store,但Vuex的构造函数必须是大写开头的Vuex.Store(前提是你已经正确导入了Vuex),否则会直接报错找不到构造函数。
4. 冗余错误:把console.log塞进commit里
commit是用来触发mutation的工具方法,不能把console.log作为参数传进去,这毫无意义,应该单独写在then回调里做调试输出。
修正后的完整代码
// 先确保你已经安装并导入了Vuex和Axios import Vuex from 'vuex' import axios from 'axios' export const store = new Vuex.Store({ state:{ posts: [], }, mutations:{ getallpost(state, posts) { state.posts = posts } }, actions: { getallpost: ({ commit }) => { axios.get('https://jsonplaceholder.typicode.com/posts') .then(function (response) { // 正确的commit用法:第一个参数是mutation名称,第二个是要传递的数据 commit('getallpost', response.data) // 单独做调试输出 console.log('Data: ', response.data); }) .catch(function (error) { console.log(error); }); }, } });
额外注意事项
- 确保已经通过
npm install vuex axios安装了依赖包 - 在Vue组件中调用这个action时,要用
this.$store.dispatch('getallpost'),或者用mapActions辅助函数简化调用
这样修改后,就能正常把API返回的posts数据存入Vuex的state中了。
内容的提问来源于stack exchange,提问作者user9563422
相关产品推荐
相关产品推荐

