首页 > 解决方案 > 为什么创建Vue组件时我的数组未定义?

问题描述

我无法理解为什么我的 Vue 组件中未定义数组。这是流程:

  1. 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:

enter image description 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.

标签: javascriptvue.jsvue-component

解决方案


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...


推荐阅读