Javascript 访问已创建函数中的axios响应数据-Vue2
从API获取类别,将其响应保存在数据变量Javascript 访问已创建函数中的axios响应数据-Vue2,javascript,vue.js,axios,Javascript,Vue.js,Axios,从API获取类别,将其响应保存在数据变量categories中,然后尝试在mounted()中使用响应数据: 但出现错误:无法读取未定义的属性“id”。我想axios的承诺是异步的,这就是为什么我不能在创建的或装载的中使用它的响应。如何正确访问它的响应 我的操作的目的是在页面加载时设置默认类别,这样页面就不会为空,因为若并没有选择类别,我不会显示任何项目 showArticles方法: showArticles (id) { return axios.get(globalConfig.FAQ
categories
中,然后尝试在mounted()
中使用响应数据:
但出现错误:无法读取未定义的属性“id”
。我想axios的承诺是异步的,这就是为什么我不能在创建的或装载的中使用它的响应。如何正确访问它的响应
我的操作的目的是在页面加载时设置默认类别,这样页面就不会为空,因为若并没有选择类别,我不会显示任何项目
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)
})
}
您必须等待fetchCategories
返回的承诺,才能使用进行解析。然后
:
this.fetchCategories()
.then(() => this.showArticles(this.categories[0].id))
或者如果您可以使用等待
/异步
:
async created () {
await this.fetchCategories()
this.showArticles(this.categories[0].id)
}
但是您可能想使用监视:
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()
}
Create
函数在挂载和方法之前创建,因此在第一个,您可以使用mounted
代替create
第二步,您可以调用Created
中的API代替方法
,然后将响应存储在store函数中,因为在装载之前您没有访问数据变量
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)
})
}
}
何时以及如何调用fetchCategories
?当fetchCategories
当时不太可能被调用时,为什么要在create
中执行this.showArticles(this.categories[0].id)
。请显示一个最小、完整的代码片段,以便理解代码流。抱歉,忘记添加fetchCategories()
call。现在添加,然后等待fetchCategories
this.fetchCategories().then(()=>this.showArticles(this.categories[0].id))
.Thatthis.showArticles(this.categories[0].id)返回的承诺
看起来非常可疑,看起来您试图以一种不应该在vue中解决问题的方式来解决问题。您介意分享showArticles
的功能吗?我同意可能有更好的方法来做这件事。对我的任务来说,watch
是不是太过分了?Async/Await对我来说看起来很优雅,使用它有什么缺点吗?@AlexanderKim,如果你做的是用this.showArticles
和this.categories[0]进行初始调用,那么我会使用categories
,因为它是自我解释的。如果您以后查看代码并进行重构,可能会决定在另一个地方使用类似于商店的vuex进行fetchCategories
,然后watch
可以保持不变,您只需删除您创建的@AlexanderKim,或者使用watch
调用此。showArticles
由您调用this.showArticles
的实际事件驱动。使用this.fetchCategories()。然后(…)
您预期的事件将调用它。因此,使用this.fetchCategories()。然后(…)
,您需要知道它确实会改变this.categories
。
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)
})
}
}