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

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

Adjusting the backdrop hues

My goal is to change the background colors of my website by cycling through all possible combinations. However, I'm encountering issues with my code and can't figure out what's wrong. var red = 0; var green = 0; var blue = 0; do { do ...

What is the best way to manage the back button using jQuery?

I'm currently facing a challenge when it comes to managing the Browser's History. While plugins like History.js can be helpful for smaller tasks, I find myself struggling with more complex scenarios. Let me provide an example: Imagine I have a m ...

Challenges with ColdFusion's floating point calculations

I am encountering an issue with my program where it is not displaying two decimal points properly. For example, when I enter 140.00, it shows as 140.0. Strangely, if I enter 140.15, it displays correctly as 140.15. It seems to consistently drop the zero. B ...

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

Display a substitute image if there is no internet connection available to load the Google Map Canvas

I have a WebApp that runs locally, but it's possible that users may not always have access to 3G/WiFi when using the app. This means that the Google Map will not load without an internet connection since it requires the web API. In order to provide a ...

How can I implement a feature in React.js where clicking a button triggers a Canvas to draw something?

I am trying to implement a <button> component that will trigger a specific function to draw on my HTML5 Canvas element. This is how the project files are structured and how I have passed the necessary props -> The main drawing function is locate ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

Downloading a file through a JavaScript link in HTMLUnit: A step-by-step guide

Looking to download a file with HTMLUnit from a javascript link is proving to be quite challenging. The journey begins at this page. When clicking on the "Authenticate with Java Web Start (new method)" link, a .jnlp file is downloaded, initiating a Java pr ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

I encountered an issue while attempting to install dependencies listed in the package.json file using the npm install command

npm encountered an error with code 1 while trying to install a package at path C:\Users\HP\Desktop\workings\alx-files_manager\node_modules\sharp. The installation command failed due to issues with the sharp plugin and its ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

Stop the execution of the setTimeout function when the webpage loads in JavaScript

In my postgres database, I have a table named students for storing student information. The structure of the table is as follows: id first_name last_name time_remind 1 pers1 pers1_name 2022-07-30 21:30 2 pers2 pers2_name 2022-07-30 20:38 Current ...

Triggering jQuery events can be customized by excluding certain elements using the

Is there a way to hide the div "popu" when clicking on the img "tri"? I've tried using .not() since the img is a child of the div popu, but it didn't work. Also, I need to make sure that clicking on the div "textb" does not trigger the hide actio ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

Issue: Bidirectional binding functionality is not functioning properly within the user interface modal

I'm currently working on displaying data in a modal, but I'm facing issues with getting two-way binding to work properly. In my HTML code: <div class="cta-actions"> <div class="action"><a class="btn btn-lg btn-max">Send a pa ...

ERROR: Module 're2' not found in './build/Release/re2' (npm)

After receiving suggestions from sonarQube, I am attempting to switch out my original regular expression with RE2. However, upon installation, the following error message appears: Error: Cannot locate module './build/Release/re2' Important note ...

Issue with Guild Member Add functionality in discord.js is not functioning as expected

I'm facing an issue with my code where the bot does not send a welcome message when a user joins, despite having everything set up correctly. Even when a user leaves, there is no farewell message being sent either. Here is the code I am using: bot.on ...

I am interested in incorporating pinia state management into my Vue 3 project

I'm currently working on implementing pinia state management in Vue 3, but I've encountered the following error: Module not found: Error: Can't resolve 'src/stores/cart' in 'C:\Users\Ali Haider\theme-project&b ...

Aligning a div vertically in the center of its parent container

I am trying to vertically align a child element within its parent element <!DOCTYPE html> <html> <head> <title>Test</title> <style type="text/css"> #body { font-family: sans-serif, arial, 'Roboto'; } #outer ...