Reputation: 1302
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.
This is my customers component.
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){
}
})
}
}
}
This is result of 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')
Upvotes: 1
Views: 3391
Reputation: 73609
Try following:
methods: {
getCustomerList () {
console.log(this)
var that = this
axios.get('/api/customers')
.then((res)=>{
if(res.status === 200){
//use that here instead of this
}
})
}
}
Upvotes: 2