Vue axios 承诺范围未绑定到当前组件
Vue axios promise scope is not binding to current component
如何在方法对象中绑定函数。我相信如果我使用箭头函数,它应该会自动绑定当前对象。但是,它有自己的范围。因此,我无法在 http get 请求后更新数据变量。
这是我的客户组件。
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)..
的结果
这是我的 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
}
})
}
}
如何在方法对象中绑定函数。我相信如果我使用箭头函数,它应该会自动绑定当前对象。但是,它有自己的范围。因此,我无法在 http get 请求后更新数据变量。
这是我的客户组件。
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)..
的结果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
}
})
}
}