问题描述
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 调用的 this.$store.state
处理程序中对 then()
的引用失败。
这是为什么?如何将我的 axios 请求收到的数据发送到 Vuex 商店?
解决方法
在普通函数中添加回调时无法访问全局对象,因此需要将其更改为箭头函数
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((response) => { // change it to arrow function
console.log('here')
console.log(this.$store.state.lang+' 2')
})
}