2017-01-20 7 views
1

メソッドオブジェクトの関数をバインドする方法。矢印機能を使うと、現在のオブジェクトに自動的にバインドするはずです。しかし、それは独自の魔法を持っています。したがって、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

関連する問題