javascript - 为什么创建Vue组件时我的数组未定义?
问题描述
我无法理解为什么我的 Vue 组件中未定义数组。这是流程:
- SelectCategories.vue 组件使用路由器推送到 Quiz.vue 组件。这里我使用 props 将数据传递给 Quiz 组件。这是如何完成的:
else {
this.$router.push({
name: 'quiz',
params: {
items: selectedCategories
}
})
}
我们继续到 Quiz.vue 组件,我在创建的生命周期钩子上执行以下操作:
async created() {
for (const item of this.items) {
var questions = await QuestionService.getQuestionsByCategory(item);
this.questions.push(questions);
console.log(this.questions);
}
}
QuestionService 访问数据库并获取一些信息,这些信息被推送到我在此处定义的问题数组中:
export default {
name: 'quiz',
props: ['items'],
data: function() {
return {
questions: [],
error: '',
};
}
最后,我尝试使用 h1 访问模板中的这些数据:
<h1>{{questions[0][0].description}}</h1>
但是,我最终遇到以下错误:
TypeError:无法读取未定义的属性“0”
我在控制台中看到的是:
{{问题[0][0].description}}
Is happening before I populate the questions array in the created life cycle hook. As you can see here:
It is my understanding that created is called before the template, but I might be wrong. What I want to accomplish is to have the functionality in created() have happen before the template is loaded, so the array gets populated first. Thank you for the help.
解决方案
What I want to accomplish is to have the functionality in created() have happen before the template is loaded
.. this is not possible. Read more on JS asynchrony. await
does not block the execution of whole app. created()
hook just returns promise and is scheduled to continue when async call finishes.
Only way is to write your template in a way that the data are not present at first and will come later...
推荐阅读
- autotools - 运行 autoconf 时将变量替换为 m4 宏
- java - HotSpot JVM的GC在什么情况下会将内存释放回OS?
- java - Hibernate DAO 无法使用带有 Spring Boot 和 thymeleaf 的下拉列表保存外键,我不想使用 jpa
- laravel - Laravel:从多个表中提取数据
- javascript - 使用键列表创建对象
- android - 在第一个 viewType 上收到 DiffUtil 有效负载数据,但我需要第二个 Viewtype
- ios - 反应原生 ios 创建可操作的通知
- amazon-web-services - AWS Eventbridge:捕获所有事件的模式
- python - Matplotlib 视图限制最小值小于 1,具有 2 个不同的比例图
- java - 邮寄图像视图而不将其保存在java中