[英]Vuejs component cannot access its own data
main component: 主要组成部分:
<template>
<spelling-quiz v-bind:quiz="quiz"></spelling-quiz>
</template>
<script>
var quiz = {
text: "blah:,
questions: ['blah blah']
}
import spellingQuiz1 from './spellingQuiz1.vue';
export default {
components: {
spellingQuiz: spellingQuiz1
},
data: function(){
return{
quiz: quiz
}
}
};
</script>
spelling-quiz component - HTML 拼写测验组件-HTML
<template>
<div>
<br>
<div v-for="(question, index) in quiz.questions">
<b-card v-bind:header="question.text"
v-show="index === qIndex"
class="text-center">
<b-form-group>
<b-form-radio-group
buttons
stacked
button-variant="outline-primary"
size="lg"
v-model="userResponses[index]"
:options="question.options" />
</b-form-group>
<button v-if="qIndex > 0" v-on:click="prev">
prev
</button>
<button v-on:click="next">
next
</button>
</b-card>
</div>
<b-card v-show="qIndex === quiz.questions.length"
class="text-center" header="Quiz finished">
<p>
Total score: {{ score() }} / {{ quiz.questions.length }}
</p>
</b-card>
</div>
</template>
spelling-quiz component - JS 拼写测验组件-JS
<script>
export default{
props:{
quiz: {
type: Object,
required: true
},
data: function(){
return{
qIndex: 0,
userResponses: Array(quiz.questions.length).fill(false)
};
},
methods:{
next(){
this.qIndex++;
},
prev(){
this.qIndex--;
},
score(){
return this.userResponses.filter(function(val){return val == 'correct'}).length;
}
}
}
};
</script>
I am getting the following error: 我收到以下错误:
[Vue warn]: Property or method "qIndex" is not defined on the instance but referenced during render.
[Vue警告]:属性或方法“ qIndex”未在实例上定义,但在渲染期间被引用。 Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
通过初始化属性,确保在data选项中或对于基于类的组件,此属性都是反应性的。
I am also getting the same error for "userReponses". 我也收到“ userReponses”相同的错误。
I do not understand the error, and I have some research but the examples do not really apply to my issue. 我不理解该错误,并且进行了一些研究,但是这些示例并不真正适用于我的问题。
Question: 题:
Why is my data not accessible? 为什么我的数据无法访问? If I refer to just this component it works, but as a child component it throws this error.
如果我仅引用此组件,那么它将起作用,但是作为子组件,它将引发此错误。 I am not sure how I can fix it.
我不确定该如何解决。
You have a missing }
after the props. 道具后您缺少
}
。 Currently your data
attribute live in your props
attribute. 目前,您的
data
属性存在于props
属性中。 data
should live on the root object. data
应位于根对象上。 Should be structured like this: 应该这样构造:
export default {
name: "HelloWord",
props: {
quiz: {
type: Object,
required: true
}
},
data: function() {
return {
test: 100
};
},
methods: {
next() {},
prev() {},
score() {}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.