开发者问题收集

Vuejs 组件无法访问自身的数据

2018-08-21
1425

主要组件:

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

拼写测验组件 - 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>

拼写测验组件 - 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>

我收到以下错误:

[Vue warn]: Property or method "qIndex" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

我也收到了“userReponses”的相同错误。

我不明白错误的原因,我进行了一些研究,但这些示例并不适用于我的问题。

问题:

为什么我的数据无法访问?如果我仅引用此组件,它可以正常工作,但作为子组件,它会引发此错误。我不确定如何修复它。

1个回答

在 props 后面缺少 。目前,您的 data 属性位于 props 属性中。 data 应位于根对象上。应按如下方式构建:

export default {
  name: "HelloWord",
  props: {
    quiz: {
      type: Object,
      required: true
    }
  },
  data: function() {
    return {
      test: 100
    };
  },
  methods: {
    next() {},
    prev() {},
    score() {}
  }
};
Jeremy Walters
2018-08-21