Vue Axios Promise范围未绑定到当前组件 [英] Vue axios promise scope is not binding to current component
本文介绍了Vue Axios Promise范围未绑定到当前组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在方法对象中绑定函数.我相信如果使用箭头功能,它将自动与当前对象绑定.但是,它有自己的scrope.因此,在http get请求之后,我无法更新数据变量.
How to bind functions in methods object. I believe if I use arrow function, it should auto bind with current object. However, it has its own scrope. Therefore, I cannot update data variables after http get request.
这是我的客户组件.
import axios from 'axios';
export default {
data () {
return {
customers: 'temp ',
loading: 'false',
error: null,
}
},
created () {
console.log(this)//this is fine
this.getCustomerList()
},
watch: {
'$route': 'getCustomerList'
},
methods: {
getCustomerList: () => {
console.log(this)
axios.get('/api/customers')
.then((res)=>{
if(res.status === 200){
}
})
}
}
}
这是console.log(this)的结果.
This is result of console.log(this)..
这是我的app.js文件
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Customers from './components/Customers/Customers.vue'
const router = new VueRouter({
mode: 'history',
base: __dirname,
history: true,
routes: [
{ path: '/customers', component: Customers }
]
})
new Vue ({
router
}).$mount('#app')
推荐答案
尝试以下操作:
methods: {
getCustomerList () {
console.log(this)
var that = this
axios.get('/api/customers')
.then((res)=>{
if(res.status === 200){
//use that here instead of this
}
})
}
}
这篇关于Vue Axios Promise范围未绑定到当前组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文