2017-08-23 42 views
0

学习VueJS并尝试对组件加载进行简单的API调用,以将回购列表放到我的页面上。当我拨打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

只需 '异步getRepos(){' – Reiner

回答

1

这只是因为你在这里使用了箭头函数,所以this.reposthis被绑定到窗口对象。将async() => {}更改为async function() {}将帮助您克服它。

参见demo

注意,不应该使用的箭头函数来定义的方法(例如,加:()=> this.a ++)。原因是箭头函数绑定父上下文,所以这不会是你期望的Vue实例,而this.a将是未定义的。

reference

+0

谢谢!我不能相信我错过了这一点。 – Anthony

0

另一种方法使用爱可信的呼叫与Vue公司则()方法:

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); 
}); 
}, 
相关问题