Include an item in a Vuetify model's array of objects

Currently, I am attempting to store the value of a dynamically loaded radio button into an array of objects. These radio buttons serve as options for a set of questions within a form, and my desired output is as follows:

[{"question1":{
   "selected": <id>,
   ...
},...]

However, I am unsure of how to define the data or reference it using the v-model attribute of the radio group.

Below is my current approach:

<v-radio-group v-model="answers[question.question_id]">
  <v-row justify="center">
    <v-col v-for="option in question.options" :key="option.option_id">
      <v-radio
        :label="option.option_text"
        :name="question.question_id"
        :value="option.option_id"                      
      ></v-radio>
    </v-col>
  </v-row>
</v-radio-group>

And here is the corresponding data section:

data: () => ({
    ...
    answers: [],
    ...
  }),

After implementation, what I am currently obtaining looks like: [answer_id1, answer_id1...], which is close to the desired result but not exactly what I need.

Answer №1

One possible approach is as follows:

<template>
  <v-layout column>
    <v-radio-group v-model="questions[questionIndex][currentQuestionId].selected">
    <v-row justify="center">
      <v-col v-for="(option,i) in questions[questionIndex][currentQuestionId].options" :key="i">
        <v-radio :label="option.text" :name="currentQuestionId" :value="option._id"></v-radio>
      </v-col>
    </v-row>
  </v-radio-group>
  <v-btn @click="handleClickButtonNext">next question</v-btn>
  <v-btn @click="handleClickButtonPrev">previous question</v-btn>
  </v-layout>
</template>
<script>
export default {
  data() {
    return {
      questions: [
        {
          question0: {
            selected: null,
            options: [
              {
                text: "text 1",
                _id: 1
              },
              {
                text: "text 2",
                _id: 2
              },
              {
                text: "text 3",
                _id: 3
              }
            ]
          }
        },
        {
          question1: {
            selected: null,
            options: [
              {
                text: "text 2",
                _id: 2
              },
              {
                text: "text 3",
                _id: 3
              },
              {
                text: "text 4",
                _id: 4
              }
            ]
          }
        },
      ],
      questionIndex: 0
    };
  },
  computed: {
    currentQuestionId() {
      return "question" + this.questionIndex;
    }
  },
  methods: {
    handleClickButtonNext() {
      if (this.questionIndex < this.questions.length-1) this.questionIndex++;
    },
    handleClickButtonPrev() {
      if (this.questionIndex > 0) this.questionIndex--;
    },
  }
};
</script>

Additional context:
questionIndex - keeps track of the current question index
currentQuestionId - provides the current question id

handleClickButtonNext / handleClickButtonPrev
- enables navigation between questions

This method displays only one question at a time.

If you prefer to loop through all questions without tracking an index, another option is to modify the code:

<template>
  <v-layout column>
    <v-radio-group
      v-for="(question, j) in questions"
      :key="j"
      v-model="question[`question${j}`].selected"
    >
      <v-row justify="center">
        <v-col v-for="(option,i) in question[`question${j}`].options" :key="i">
          <v-radio :label="option.text" :name="`question${j}`" :value="option._id"></v-radio>
        </v-col>
      </v-row>
    </v-radio-group>
  </v-layout>
</template>
<script>
export default {
  data() {
    return {
      questions: [
        {
          question0: {
            selected: null,
            options: [
              {
                text: "text 1",
                _id: 1
              },
              {
                text: "text 2",
                _id: 2
              },
              {
                text: "text 3",
                _id: 3
              }
            ]
          }
        },
        {
          question1: {
            selected: null,
            options: [
              {
                text: "text 2",
                _id: 2
              },
              {
                text: "text 3",
                _id: 3
              },
              {
                text: "text 4",
                _id: 4
              }
            ]
          }
        }
      ]
    };
  }
};
</script>

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

The D3.extent() function is raising a TypeError because it is unable to iterate over the

I have been struggling with this issue for the past few hours, and I could really use some help. I'm not very familiar with using D3 in conjunction with React. Essentially, I have an anomaly detection algorithm running on the backend Flask App that r ...

Error message appears when trying to render a shallow mock of a React.Component that extends MyInterface with any type

Encountering an Issue with Component Mocking When attempting to mock a component, I am receiving the following error message: "Conversion of type '{ props: { index: number; AssignmentTitle: string; AssignmentDescription: string; AssignmentUtilizedHou ...

Utilizing React JS and lodash's get method within a single function

Is it possible to display two string objects in the same line using Lodash get? Can I achieve this by chaining (_.chain(vehicle).get('test').get('test2))? Below is a snippet of the JSON file: { "results": [ { " ...

Discovering which particular check in the Express Validator is causing the errors can be done by following these steps

I am currently developing a web application that requires an admin user to create new users. The admin user's username and password are stored in the .env file, and I am utilizing the dotenv package for this purpose. However, I am facing an issue when ...

What is the process for displaying a vnode (slot of a vue component) and attaching it to a specific element?

Consider the scenario where a dialog component is present. ... <dialog> <div> {{data}} </div> </dialog> ... Because of the stack context limitations, it can be challenging to keep the dialog always at the topmost position ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Unexpected request causes a dilemma during the karma test for an Angular directive

Let's discuss a straightforward directive: 'use strict'; angular .module('app') .directive('ngEmailMask', ngEmailMask); function ngEmailMask() { var directive = { replace: true, restrict: 'EA', ...

Check to see if one string is beginning to resemble another string

Within an array, I have stored a set of keywords. When a user correctly types one of these keywords, the pass() function is executed. This validation occurs during each keystroke event (on key up), as I compare the user input to the items in the array. To ...

Programme for Server Login

After creating my own server, I attempted to implement a login feature to restrict access to its files. Unfortunately, using Javascript for this task proved to be insecure as usernames and passwords could easily be viewed in the source code: <form name ...

Steps to turn off the automatic completion feature for orders in WooCommerce on your WordPress website

Looking for assistance with changing the order status from completed to processing. When an order is placed, it automatically goes to completed status which is not the desired outcome. The status should change based on the virtual product purchased. I wou ...

How can I make Backbone.js execute a function following the creation of a Collection?

It seems like I may not be grasping the full picture here, but let me lay out my current understanding: I have a Model that holds 'all' the data (JSON retrieved from a single URL). This model contains one or more Collections which are populated ...

What is the best way to represent objects in a user interface?

Currently, I have some information stored in the following format: data : { full_name: 'John Doe', date_of_birth: '01-01-1990' } I am looking to display this data in a table-like format that resembles: Full Name: John Doe Date Of B ...

Leveraging Vue components for populating table information within a Vue-exclusive application

I am currently working on developing a front-end web application using Vue. One of the components in this application renders a table, and I want to populate some of the table data using a child component within a loop for each row in the table body. Pare ...

Listen up, Javascript keyboard input recorder

I am aiming for the search bar to pop up when you type. The code below is functioning, but I am facing an issue where the search bar pops up even when typing in a different input field, such as the comment input. Is it feasible for the search bar not to ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

Incorporate a Fadein effect into the current CSS for mouseover link interaction

Is there a way to enhance my current css code for a mouseover link with a background image by adding a fade in and out effect? What's the most effective method to achieve this using jquery? .sendB { width: 100%; height: 125px; background: ...

What are the best practices for effectively utilizing the nodejs Stream API?

I am currently working on an application that reads input from various sources, including files, sockets, and other parts of the same program that produce buffers or strings. While I have successfully handled sockets and files using node's Stream API ...

Retrieving a numeric attribute from a JSON structure

Recently, I encountered an issue with a PHP multidimensional array that I converted to JSON using JSON_encode(). Since I am working with Drupal, the arrays often contain keys that look like this: $some_array['und']['0']['value&a ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

I am having trouble adding multiple items on different occasions - is it something to do with JQUERY

I have been working on a dynamic website that loads Firebase values into a table. However, I encountered an issue where the data does not appear when going back to the orders page after visiting another page. After some testing, I found that placing a but ...