Reputation: 2010
I am getting this error Error in data(): "TypeError: Unable to get property 'questions' of undefined or null reference"
on the template page. What am I doing wrong here I could not resolve the error. It appears to be quiz.questions is not recognized by the template even though data() has the quiz variable. Below is the vue routing and the template Question.vue that needs to be rendered on the front page.
Routing
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>
Upvotes: 0
Views: 511
Reputation: 1295
Your userResponses variable should be a computed property, so remove it from data and add this between data() and methods :
computed:{
userResponses(){return Array(this.quiz.questions.length).fill(false)}
}
Check the documentation for more informations about computed properties : https://fr.vuejs.org/v2/guide/computed.html
Upvotes: 1
Reputation: 2164
It appears that your vue instance already ran before the data was loaded.
Try adding a v-if
to check if the data already exists before vue loads the data.
<div v-if="quiz" v-for="(question, index) in quiz.questions" class="ques_block">
</div>
Upvotes: 0