Generate an array of responses within a child component and then send this array to the parent component using Vue.js 2

Currently, I am in the process of creating a survey using Vue 2. My goal is to construct and emit the answers array to a parent component named Evaluation. You can view the structure of this array here: https://pastebin.com/rLEUh56a

Within my project, there exists a component known as QuestionItem.vue, which serves as the child component of Evaluation. Details regarding this component can be found here: https://pastebin.com/RFPgKs5Q

The format of the answers array needs to adhere to specific criteria for successful transmission to the API:

answers: [
  {
    questionId: "6a9ad778-aacf-4e60-9610-37a767700b9f",
    questionOptionIds:[
      "1bc35f6c-900a-4764-84ee-23531e46e638",
    ],
    answer: null
  },
  {
    questionId: "d1c3f4f0-9525-4e6e-bb81-599d84b5cb02f",
    questionOptionIds:[],
    answer: "answered value"
  },
]

In situations where the question.type is categorized as text, range, stars, or faces, it is required that the questionOptionIds remain empty while the answer property contains the user's response. Conversely, if the question.type corresponds to radio or check, the answer should be null, and the questionOptionIds must reflect the selected option.

I am currently facing challenges in constructing this array based on the information inputted in the QuestionItem.vue component. Any guidance on how to accomplish this task would be greatly appreciated. Thank you for your time and have a wonderful day!

Answer №1

Using v-model for managing answers in your QuestionItem component is not recommended:

<QuestionItem 
                                v-for="(question, index) in questions"
                                :key="index"
                                :question="question"
                                :index="questionIndex"
                                v-model="answers"
                                class="flex-none w-full"
                            />

v-model assigns the emitted input value from the child directly to answers, but since answers is an array of answers instead of a single answer, this approach doesn't make sense.

To address this issue, you need to create a custom event handler in the parent component. Here's an example:

// in Evaluation.vue methods
answerChanged(answer) {
    // Remove existing answer if it already exists in the array
    answers = answers.filter(a=>a.questionId != answer.questionId);
    // Add the provided answer
    answers.push(answer);
}

Instead of using v-model, utilize the event handler as shown below:

 <QuestionItem 
                                v-for="(question, index) in questions"
                                :key="index"
                                :question="question"
                                :index="questionIndex"
                                @input="answerChanged" // Bind the event handler
                                class="flex-none w-full"
                            />

Lastly, ensure that the questionId is included in the emitted value. Below is a general representation which may need adjustments based on your specific requirements:

 watch: {
    questionValue(newValue) {
        // Emitting the desired value for a single answer within our parent answers array
        this.$emit('input', {
           questionId: question.id,
           questionOptionIds:question.options,
           answer: newValue
        })
    },
},

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

Unexpected issue with Ustream JSON API and jQuery

Recently, I attempted to execute the following jQuery code: var query = 'http://api.ustream.tv/json/channel/masaiblog/getValueOf/status?jsonp=?'; $.getJSON(query, function(data) { if (data['results'] == 'live') { ...

Issues with border/padding and overlay in Packery Grid Layout

After spending some time working on a grid layout using the metafizzy isotope packery mode, I have encountered a few issues. To illustrate my problem, I have provided a link to a codepen below: http://codepen.io/anon/pen/EgKdpL Although I am satisfied wi ...

Experiencing trouble with detecting intersections using the Three.js raycaster

After successfully writing a code to intersect some objects, I encountered an issue when adding a canvas along with other div elements in the HTML document. Now, there seems to be no intersection on the object. You can observe this live example here. If yo ...

`Using Twitter Bootstrap in mobile app development with javascript`

I have been utilizing Twitter Bootstrap 2.3 on one of my websites and I appreciate its responsiveness and use of media queries for mobile devices. However, I have noticed a lack of mobile-specific features, particularly linked listviews. In order to addres ...

Having trouble getting my app.get calls to work in the new Node Express project

Recently, I kicked off a new project and encountered a perplexing issue - my app.get method simply refuses to be invoked. The site keeps loading indefinitely without any content being displayed. Initially, I copied and pasted the code from another project ...

Unable to retrieve the initial return value from the function that has been promisified

Previously, the code functioned correctly but was not properly promisified. const express = require('express'); function runServerAndReturn() { app = express(); console.log('Before starting server'); const server = app.lis ...

Do not start Chart.js on the Y-Axis

As of now, this is the current appearance of the code which includes a Chart.js first image preview. I am seeking advice on how to prevent my data chart from starting at the Y axis. The result of the code can be viewed below. var ctx = document.getEl ...

What is the process for a server to transmit a JWT token to the browser?

Here is an example response sent to the browser: HTTP / 1.1 200 OK Content - Type: application / json Cache - Control : no - store Pragma : no - cache { "access_token":"MTQ0NjJkZmQ5OTM2NDE1Z ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

Establish Vue and the Vue CLI

I'm currently in the process of setting up a new Vue project. I started off by installing @vue/cli using the following command: PS D:\OpenServer\domains\vue3-example> npm install -g "@vue/cli" Next, I attempted to create t ...

You must provide a value for a v-bind expression; an empty value was detected in "v-bind:items"

I am completely new to using Vue. I have a vue component that I am working with, where I pass some objects through the component if they are available. Here is an example of how I'm using it: <form :languages='{{ json_encode($languages) }}&apo ...

Verifying multiple button selections in a Django template

Within my django template, there is a block of code that appears like this: {% block b %} { % for foo in foos %} { % if foo.some_variable % } <form method="LINK" action="{% url "some_view" foo.id %}" id="button"> ...

The object filtering process is experiencing issues due to the presence of a null value in the column

I am trying to extract object data based on a specific value from an array. While the code snippet below works well when there are no null values, it fails to work properly when encountering null values in the column. For reference, you can check out this ...

Having trouble resolving the signature of a class decorator when invoked as an expression with @Injectable in Angular

Error Message: Unable to resolve the signature of a class decorator when called as an expression. The argument type 'ClassDecoratorContext' is not compatible with the parameter type 'string | symbol | undefined'. After creating a book ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

The system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

Deactivate every textarea within a loop when adding a comment to a post using Vue.js

How can I modify my code so that only one text area opens at a time when I click the comment button instead of all text areas opening simultaneously? // Sample View <div id="app" v-cloak> <div v-for="post ,key in posts" > @{{post.content ...

Angular 2 click event with changing function name

Even though this question seems simplistic, I'm having trouble figuring it out. As someone new to Angular 2, I've tried various combinations of {}, [], and () brackets to make the following work: <button (click)="this.action">Click me</ ...

How to send configuration data to an external library in Angular 6 in the app.module.ts file

My goal is to provide basic configuration settings to an external or third-party module. These settings are stored in a JSON file for easy modification across different environments without the need to rebuild the code. import { BrowserModule } from &apos ...

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...