javascript - 如何处理 vuex 存储以从 rest api 获取数据?
问题描述
我正在使用 Vuex 来处理我的应用程序状态。
我需要向 rest api 发出 Ajax Get 请求,然后显示一些对象列表。
我正在调度一个从服务器加载此数据的操作,但是我不知道如何在组件上处理它。
现在我有这个:
//component.js
created(){
this.$store.dispatch("fetch").then(() => {
this.objs = this.$store.state.objs;
})
}
但我不认为将传入数据分配给本地属性是处理存储数据的正确方法。
有没有办法更好地处理这个问题?也许使用mapState?
谢谢!
解决方案
There are many ways you can do it, you must experiment and find the one that fits your approach by yourself. This is what I suggest
{ // the store
state: {
something: ''
},
mutations: {
setSomething (state, something) {
// example of modifying before storing
state.something = String(something)
}
},
actions: {
fetchSomething (store) {
return fetch('/api/something')
.then(data => {
store.commit('setSomething', data.something)
return store.state.something
})
})
}
}
}
{ // your component
created () {
this.$store
.dispatch('fetchSomething')
.then(something => {
this.something = something
})
.catch(error => {
// you got an error!
})
}
}
For better explanations: https://vuex.vuejs.org/en/actions.html
Now, if you're handling the error in the action itself, you can simply call the action and use a computed property referencing the value in the store
{
computed: {
something () { // gets updated automatically
return this.$store.state.something
}
},
created () {
this.$store.dispatch('loadSomething')
}
}
推荐阅读
- excel - 过滤数据透视表的最后一项 (vba)
- javascript - Webpack 组合完所有东西后再次运行 Babel?
- android - 意外令牌':'.parse - 反应原生Android
- java - Spring AOP:@annotation() 切入点与类型注释不匹配
- reactjs - 如何将底部导航器与抽屉导航器集成
- mysql - 使用 sql 审计 .net 应用程序
- http - Safari 12 网络请求时间线未显示重定向
- plsql - 通过 PL/SQl 过程调用 odi Mappig
- javascript - 使用 Jquery 的点击事件未开始下载
- python - 如何修复我的代码以便能够创建新的存储库