嗨,我是 vuejs 和 axios 的新手,我想获取我的 axios 并将响应存储在变量中并将该变量设置为全局变量,以便我可以在代码之外访问它。然而,当我在 console.log 时,它总是给我未定义。有人可以帮我吗?谢谢你。
这是代码:
async created() {
let result;
this.$store
.dispatch('getAllProduct')
.then((responseOne) => {
// console.log("PRODUCT", responseOne.data.data)
result = responseOne.data.data
})
.catch((error) => {
console.log('ERROR USER RESPONSE ', error)
})
console.log('t', result)
},
由于您添加async
到 created 您应该await
响应:
async created() {
let result;
try {
const responseOne = await this.$store.dispatch('getAllProduct')
result = responseOne.data.data
}
catch(error) {
console.log('ERROR USER RESPONSE ', error)
}
console.log('t', result)
},
如果你不想使用async/await
,你应该result
在 data 选项中定义并在then
回调中更新:
data(){
return{
result:null
}
},
watch:{
result(newVal){ // watch the result property
console.log(newVal)
}
},
created() {
this.$store
.dispatch('getAllProduct')
.then((responseOne) => {
// console.log("PRODUCT", responseOne.data.data)
this.result = responseOne.data.data
})
.catch((error) => {
console.log('ERROR USER RESPONSE ', error)
})
},
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句