2017-08-23 16 views
0

VueJSを学び、部品ロード時に簡単なAPIコールを実行して、reposのリストをページに配置しようとしています。 created()メソッドからthis.reposを呼び出して設定すると、問題はありません。しかし、方法として設定してからthis.getReposから呼び出すと何も起こりません。エラーなし、何もありません。私はVueJSについて何が欠けていますか?VueJSがcreated()関数からメソッドを呼び出さないのはなぜですか?

これは動作します:

data:() => ({ 
    msg: 'Github Repos', 
    ok: 'Im practically giving away these repos', 
    repos: [], 
    }), 
    methods: { 
    }, 
    async created() { 
    const repos = await axios.get('https://api.github.com/orgs/octokit/repos'); 
    this.repos = repos.data.map(repo => 
     `<div class="box"><a href="${repo.html_url}"> 
     ${repo.name} 
     </div>`, 
    ); 
    }, 

これは動作しません:

data:() => ({ 
    msg: 'Github Repos', 
    ok: 'Im practically giving away these repos', 
    repos: [], 
    }), 
    methods: { 
    getRepos: async() => { 
     const repos = await axios.get('https://api.github.com/orgs/octokit/repos'); 
     this.repos = repos.data.map(repo => 
     `<div class="box"><a href="${repo.html_url}"> 
      ${repo.name} 
     </div>`, 
    ); 
    }, 
    }, 
    created() { 
    this.getRepos(); 
    }, 

任意のアイデア?ありがとう!

+0

[VueJSの可能性の重複:なぜ "この" 定義されていませんか? ](https://stackoverflow.com/questions/43929650/vuejs-why-is-this-undefined) – Bert

+0

ちょうど 'async getRepos(){' – Reiner

答えて

1

ここで矢印関数を使用して、this.reposthisがウィンドウオブジェクトにバインドされているからです。 async() => {}からasync function() {}に変更すると、それを克服するのに役立ちます。

は、あなたがメソッドを定義するには、矢印の機能を使用しないでくださいdemo

ノートを参照してください(例えばプラス:()=> this.a ++)。その理由は、矢印関数が親コンテキストをバインドするため、期待どおりのVueインスタンスではなく、this.aは未定義になります。

reference

+0

ありがとう!!!私はそれを逃したとは信じられません。 – Anthony

0

その後、()メソッド使用してVueのでAxios呼び出しを行う別の方法:

demo

created() { 
axios.get('https://api.github.com/orgs/octokit/repos', { 
    params: { 
    type: 'all', 
    }, 
}) 
.then((res) => { 
    console.log('Success Response', res.data); 
    res.data.forEach((repo) => { 
    this.repos.push({ name: repo.name, url: repo.html_url, language: repo.language }); 
    }); 
}) 
.catch((err) => { 
    console.log('Error', err); 
}); 
}, 
関連する問題