如何解决Vuex 商店不能在 axios 处理程序中使用
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')
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。