从API获取类别,将其响应保存在数据变量categories
中,然后尝试在mounted ()
中使用响应数据:
data () {
return {
categories: {}
}
}
created () {
this.fetchCategories()
this.showArticles(this.categories[0].id)
}
methods: {
fetchCategories () {
return axios.get(globalConfig.FAQCATS_URL)
.then((resp) => {
this.categories = resp.data
})
.catch((err) => {
console.log(err)
})
}
}
但是出现错误:Cannot read property 'id' of undefined
。我猜axios的承诺是异步的,这就是为什么我不能在created
或mounted
内部使用它的响应。我如何正确访问它的响应?
我的目的是在页面加载时设置默认类别,因此页面不会为空,因为如果未选择类别,则我不会显示任何项目。
showArticles
方法:
showArticles (id) {
return axios.get(globalConfig.FAQCATS_URL + '/' + id + '/articles')
.then((resp) => {
this.articles = resp.data
// console.log(resp)
})
.catch((err) => {
console.log(err)
})
}
答案 0 :(得分:1)
You will have to wait for the Promise returned by fetchCategories
to resolve using .then
:
this.fetchCategories()
.then(() => this.showArticles(this.categories[0].id))
Or if you can use await
/async
:
async created () {
await this.fetchCategories()
this.showArticles(this.categories[0].id)
}
But you probably want to use watch
:
data () {
return {
categories: null
}
}
watch: {
categories( newList, oldList ) {
if( !oldList ) {
// only call showArticles if categories was not et before
this.showArticles(this.categories[0].id)
}
}
}
created () {
this.fetchCategories()
}
答案 1 :(得分:0)
Create
function created before the mounted and methods, so in the first, you can use mounted
instead create
second you can call the API in the Created
instead methods
and then store the response in the store function because of you don't access to data variable
before mounted.
data () {
return {
categories: {}
}
}
mounted() {
this.fetchCategories()
}
methods: {
fetchCategories () {
return axios.get(globalConfig.FAQCATS_URL)
.then((resp) => {
this.categories = resp.data;
this.showArticles(this.categories[0].id)
})
.catch((err) => {
console.log(err)
})
}
}