Methods 为什么赢了';t VueJS是否从created()函数调用方法?
学习VueJS并尝试在组件加载时执行一个简单的API调用,以便将repo列表放到我的页面上。当我从Methods 为什么赢了';t VueJS是否从created()函数调用方法?,methods,vue.js,components,Methods,Vue.js,Components,学习VueJS并尝试在组件加载时执行一个简单的API调用,以便将repo列表放到我的页面上。当我从created()方法调用并设置this.repos时,没有问题。但如果我将其设置为一个方法,然后从this.getRepos调用它,则不会发生任何事情。没有错误,什么都没有。关于VueJS,我遗漏了什么 这项工作: data: () => ({ msg: 'Github Repos', ok: 'Im practically giving away these repos',
created()
方法调用并设置this.repos
时,没有问题。但如果我将其设置为一个方法,然后从this.getRepos
调用它,则不会发生任何事情。没有错误,什么都没有。关于VueJS,我遗漏了什么
这项工作:
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>`,
);
},
数据:()=>({
msg:'Github Repos',
好:“我实际上是在送出这些回购协议”,
回购协议:[],
}),
方法:{
},
异步创建(){
const repos=等待axios.get('https://api.github.com/orgs/octokit/repos');
this.repos=repos.data.map(repo=>
`
${repo.name}
`,
);
},
这不起作用:
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();
},
数据:()=>({
msg:'Github Repos',
好:“我实际上是在送出这些回购协议”,
回购协议:[],
}),
方法:{
getRepos:async()=>{
const repos=等待axios.get('https://api.github.com/orgs/octokit/repos');
this.repos=repos.data.map(repo=>
`
${repo.name}
`,
);
},
},
创建(){
这个.getRepos();
},
有什么想法吗?谢谢 这只是因为您在这里使用了箭头函数,所以
this.repos
的this
绑定到窗口对象。将async()=>{}
更改为async function(){}
将帮助您克服它
看
请注意,不应使用箭头函数来定义方法(例如plus:()=>this.a++)。原因是箭头函数绑定父上下文,因此这将不是您期望的Vue实例,并且这.a将是未定义的
使用then()方法使用Vue执行Axios调用的另一种方法: Just
async getRepos(){
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);
});
},