vue.js - 无法在我的组件中使用操作返回的值
问题描述
我的商店操作返回一个值,当从我的组件调用该操作时,我想检查该值。但由于某种原因,我得到的只是undefined
我从任何操作中实际返回的任何值。
为什么?
存储操作:
export const actions = {
async initialize ({ state, commit, dispatch }) {
await this.$axios.get('myEndpoint')
.then((res) => {
return true
}).catch((error) => {
return false
})
}
}
组件代码:
async mounted () {
const initializeResult = await this.initialize()
console.log(initializeResult)
}
解决方案
您必须尊重 vuex 存储模式,首先您应该创建一个可以在突变中发生突变的状态,该突变也可以在您的操作中的异步回调中提交:
export const state={
initResult:null
}
export const mutations={
SET_RESULT(state,payload){
state.initResult=payload
}
}
export const actions = {
async initialize ({ state, commit, dispatch }) {
await this.$axios.get('myEndpoint')
.then((res) => {
commit('SET_RESULT',true)
}).catch((error) => {
commit('SET_RESULT',false)
})
}
}
然后在您的组件中调度挂载钩子内的操作并使用计算属性返回状态:
computed:{
result(){
return this.$store.initResult;
}
},
mounted () {
this.$store.dispatch('initialize')
}
推荐阅读
- react-native - 如何在屏幕之间传输数据但不能在本机反应中切换屏幕
- javascript - 用 JSON 替换数组中的键和字符串
- firebase - 将带有列表的 Flutter 对象映射到 Firebase 实时数据库
- amazon-web-services - 如何修改已创建的 IAM 角色的承担角色策略?
- python - 获得时间异常后,我将如何重新启动 Web 驱动程序并继续运行脚本?
- mysql - MySQL 间隙锁行为不符合预期
- javascript - 如何在mvc的视图中传递html href内的变量
- javascript - 使用 jsPDF 将多个不同的图像添加到 PDF
- javascript - 获取api响应慢且不稳定
- angular - Angular 9 无法在日期管道之后过滤日期