fiddlest
fiddlest

Reputation: 1302

Vue axios promise scope is not binding to current component

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)..

result of console.log(this) This is my app.js file

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

Answers (1)

Saurabh
Saurabh

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

Related Questions