Vue axios promise scope is not binding to current component

家住魔仙堡 提交于 2019-12-11 07:33:44

问题


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

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

回答1:


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


来源:https://stackoverflow.com/questions/41754346/vue-axios-promise-scope-is-not-binding-to-current-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!