2017-01-20 48 views
1

如何綁定方法對象中的函數。我相信如果我使用箭頭函數,它應該自動綁定當前對象。但是,它有自己的scrope。因此,我無法在http請求後更新數據變量。Vue axios承諾範圍不與當前組件綁定

這是我的客戶組件。

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的結果(這)..

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

回答

2

嘗試以下操作:

methods: { 
    getCustomerList() { 
    console.log(this) 
    var that = this 
    axios.get('/api/customers') 
    .then((res)=>{ 
     if(res.status === 200){ 
      //use that here instead of this 
     } 
    }) 
    } 
} 
+0

這已經在與組件sc無關的錯誤範圍內OPE。 – user3882878

+0

@ user3882878做了一些更改,它在我的代碼中就像這樣工作。 – Saurabh

+0

嗯..我不應該使用箭頭功能。謝謝我剛剛實現 – user3882878