The Vuejs component finds itself unable to retrieve 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

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

<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 encountered the following error message:

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

The same error is occurring with "userReponses".

I'm puzzled by the error and have attempted some research, but the solutions I found don't seem to apply to my case.

Question:

Why can't I access my data? It works fine when just referencing this component, but as a child component, it throws this error. I'm unsure how to resolve it.

Answer №1

Don't forget to add a closing curly brace } after the props section in your code. Currently, your data attribute is nested within the props attribute. To correct this, move the data attribute to the root object like so:

export default {
  name: "Greeting",
  props: {
    user: {
      type: Object,
      required: true
    }
  },
  data: function() {
    return {
      message: "Hello"
    };
  },
  methods: {
    greet() {},
    farewell() {},
    askName() {}
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get node extensions set up without the hassle of typing in commands

As part of my internship, I am tasked with setting up a node server for the company. I have successfully installed Node on my Windows computer and now need to install plugins such as:    - nodejs-webpack    - colors &n ...

"Invalid operation" error encountered within a Flask function in Python

I am trying to store a 'person' resource in a .ttl file using a JavaScript function: Here is my SPARQL query: @app.route('/registraAnnotatore/<author>+<mail>', methods=['POST']) def registraAnnotatore(author, ...

Chartjs tooltips are displayed across all charts when hovering over a single chart

Currently, I am utilizing ChartJS in conjunction with angular. I successfully implemented a vertical line on my chart when hovering by following the example provided at How to render a vertical line on hover in chartjs. Now, I am seeking examples for crea ...

Dealing with undefined Ajax values in PHP

Every time I call the function, I receive an undefined value and it's baffling me as to what could be causing this issue. You are logged in as undefined, Error undefined Ajax script: function Submit() { console.log('asd') $.ajax({ ...

Having concerns regarding the retrieval of response data from Slice in index.js using React Redux Toolkit

I am attempting to retrieve data from an API and utilize it in my index.js file Issue: Encountering a TypeError: Cannot read properties of undefined (reading 'icon') When logging the output, I see An empty Array in index.js > response da ...

When a dropdown is clicked, it will close any other dropdowns that are currently

Upon clicking on the top menu link "menu item 01", the 3 level drop down opens as expected. Similarly, when you click on "menu item 04", the mega menu expands perfectly. However, I am looking to achieve a functionality where if the user clicks on any othe ...

Seeking assistance with prototyping JS/AJAX features

For my current project, I have been utilizing PrototypeJS. However, today I ran into a problem. I am working on creating a contact list for a module, where contacts can be added via a form or removed with a link. Below is the HTML code for the removal li ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

Prevent the end of the scroll from causing a new scroll to start?

In the code snippet provided, there are two divs. When scrolling down past the end of the blue div, the overall body/div also scrolls down. Is there a way to prevent this additional scrolling effect once reaching the scroll boundary of the blue div? For e ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

Attain worldwide reach

I'm currently facing a Scope issue that has been quite challenging to resolve. The saying goes, "a picture is worth a thousand words," and in this case, it couldn't be more true. Whenever the OK or REJ buttons trigger the reject() function, passi ...

transmitting base64 encoded information to the server only to find that the form field is returned

I am currently working on a project with a front-end developed in Vue and a back-end in Golang. For the backend service, Google App Engine is being used along with gcloud Datastore and gcloud Storage to handle data and image storage submitted through forms ...

Can you explain the contrast between aws-amplify-react and @aws-amplify/ui-react?

I have come across multiple sources recommending the use of aws-amplify-react, but in the documentation for getting started with React, I found a different package @aws-amplify/ui-react that utilizes the module withAuthentication (which is also present in ...

Firefox experiences failure with Ajax while all other browsers are functioning properly

I've seen discussions on various forums and websites regarding the issue with Firefox browser failing to refresh a CAPTCHA image created in PHP when a button is clicked. I've tried multiple scripts, all of which work perfectly in Edge, Chrome, Sa ...

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

Utilizing "Content" for Responsive Image Design in Chrome Version 33.0.1750.117

I previously implemented a method for responsive images on my website, which was working fine until the latest Chrome update. Surprisingly, it still functions properly on other browsers. //< ![CDATA[ var queries = [ ...

Problem with modals not triggering within the iDangero.us swiper

I am encountering an issue with the iDangerous.us Swiper where I cannot activate any events within the swiper-wrapper. I am attempting to trigger a modal on each slide but nothing is happening. Any Modal placed inside the swiper-wrapper does not work. I a ...

Suggestion for implementing numerous ajax countdown timers (one call per second)

I am currently developing a system with 100 countdown timers that each make an ajax call every second to retrieve the endTime from the database and update the countdown time. The reason for calling this every second is because the endTime can be altered. ...