【发布时间】:2021-03-06 16:40:05
【问题描述】:
我的 Vue 组件中的按钮成功调用了方法:
methods: {
goTestMe() {
console.log(this.$store.state.lang+' 1')
let url = 'some api url'
let headers = { headers: { 'Content-Type': 'application/json' } }
this.$axios
.get(url, headers)
.then(function(response) {
console.log('here')
console.log(this.$store.state.lang+' 2')
})
问题是这个的输出是:
en-us 1
here
什么时候应该:
en-us 1
here
en-us 2
显然,在 axios 调用的 then() 处理程序中对 this.$store.state 的引用失败了。
这是为什么?如何将我的 axios 请求收到的数据发送到 Vuex 存储?
【问题讨论】:
-
你尝试过使用异步等待吗?它可能永远不会被调用的原因是该函数完成得太快。因此,axios 请求永远不会得到解决。
-
@FloWy 这不是问题。他使用
then来异步处理promise,这基本上就是async...await在幕后的意思。约瑟夫在下面的回答是正确的。这个问题是由于this是对 promise 的执行上下文的引用,比 vue 组件的执行上下文更重要。发生这种情况是因为像这样传递function(){}表达式会更改上下文。改用() => {}箭头函数表达式将使this引用vue 组件上下文。 -
哦,对不起,我的错:D
-
谢谢你们。如果您对理解 JS 中的 async/await 和箭头函数有很好的参考,我将不胜感激。
标签: vue.js axios vuex console.log