data()中的错误:“ TypeError:无法获取未定义或空引用的属性'问题'”

时间:2019-02-13 09:21:56

标签: laravel vue.js

我在模板页面上收到此错误Error in data(): "TypeError: Unable to get property 'questions' of undefined or null reference"。我在做什么错,在这里我无法解决错误。它似乎是quiz。即使data()具有quiz变量,模板也无法识别问题。下面是vue路由和需要在首页上呈现的模板Question.vue。

路由

let routes = [
{ path: '/quiz/:id(\\d+)/', component: require('./components/Questions.vue') },

Question.vue

<template>
    <div class="ques_wrapper">
        <div v-for="(question, index) in quiz.questions" class="ques_block">

        </div>
    </div>
</template>
<script>

export default {
    data() {
         return {
          quiz: {
                title: 'My quiz',
                questions: [
                  {
                    text: "Question 1",
                    responses: [
                      {text: 'Wrong, too bad.'}, 
                      {text: 'Right!', correct: true}, 
                    ]
                  }, {
                    text: "Question 2",
                    responses: [
                      {text: 'Right answer', correct: true}, 
                      {text: 'Wrong answer'}, 
                    ]
                  } 
                ]
              },
              questionIndex: 0,
              userResponses: Array(this.quiz.questions.length).fill(false)
            }
        },

        // The view will trigger these methods on click

        methods: {

          // Go to next question

          next: function() {

            this.questionIndex++;

          },

          // Go to previous question

          prev: function() {

            this.questionIndex--;

          },

          // Return "true" count in userResponses

          score: function() {

            return this.userResponses.filter(function(val) { return val }).length;

          }

        }

    }

  </script>

2 个答案:

答案 0 :(得分:1)

您的userResponses变量应为计算属性,因此将其从数据中删除并将其添加到data()和方法之间:

computed:{
userResponses(){return Array(this.quiz.questions.length).fill(false)} 
}

查看文档以获取有关计算属性的更多信息: https://fr.vuejs.org/v2/guide/computed.html

答案 1 :(得分:0)

看来,您的vue实例已在加载数据之前运行。 尝试添加v-if,以在vue加载数据之前检查数据是否已经存在。

<div v-if="quiz" v-for="(question, index) in quiz.questions" class="ques_block">

</div>