Unlocking the nested v-for in Vuejs to access id and submit using axios

I am currently working on developing an application that utilizes a typeorm backend and a Vue.js frontend. This app is designed to collect customer data through surveys.

For this purpose, I retrieve data from my backend using an axios get request, and I intend to send the selected checkboxes via an axios post request. However, I am facing difficulty in obtaining multiple IDs for inclusion in the post request. I have included comments in my code to provide clarity on my question.

<template>
  <div>
    <p>Survey Name: {{ currentSurveys.survey_title }}</p>
    <p>Company Type: {{ currentSurveys.company.company_type }}</p>

    <div>
      <!-- First loop to fetch the data -->
      <div v-for="(currentSurvey, index) in currentSurveys" v-bind:key="index">
        <v-row align="center">
          <v-expansion-panels :popout="popout" :tile="tile">
            <!-- Second loop to process the company model -->
            <v-expansion-panel
              v-for="(currentSurvey, index) in currentSurvey.models"
              v-bind:key="index"
            >
              <!-- Third loop to access the topics -->
              <v-expansion-panel
                v-for="(currentSurvey, index) in currentSurvey.topics"
                v-bind:key="index"
              >
                <v-expansion-panel-header style="color:white">{{ currentSurvey.topic_title }}</v-expansion-panel-header>

                <!-- Fourth loop to display the questions -->
                <v-expansion-panel-content
                  v-for="(currentSurvey, index) in currentSurvey.questions"
                  v-bind:key="index"
                >
                  <div class="survey_questions">
                    <p>
                      {{ currentSurvey.questionId }} -
                      {{ currentSurvey.question_title }}
                    </p>
                    <p>{{ currentSurvey.comments }}</p>
                    <!-- Fifth loop to render answers as checkboxes-->
                    <!--I want to trigger the postAnswers() function when a checkbox is clicked and include the following data: surveyId, modelId, topicId, questionId-->
                    <!-- Obtain answerId with "isPicked" function-->
                    <div v-for="(currentSurvey, index) in currentSurvey.answers" :key="index">
                      <input
                        type="checkbox"
                        :value="currentSurvey.answerId"
                        @input="isPicked"
                        @change="postAnswer()"
                      />
                      <label>{{ currentSurvey.answerId }}</label>
                      <label>{{ currentSurvey.answer_title }}</label>
                    </div>
                  </div>
                </v-expansion-panel-content>
              </v-expansion-panel>
            </v-expansion-panel>
          </v-expansion-panels>
        </v-row>
      </div>
      <div>
        <button class="survey_submit_button">Submit</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "MySurvey",

  data: () => ({
    popout: true,
    tile: true,

    currentSurveys: [],
    picked: ""
  }),


  mounted() {
    axios
      .get(`http://localhost:3005/surveys/` + this.$route.params.id)
      .then(response => {
        this.currentSurveys = response.data;
      })
      .catch(e => {
        console.log(e);
      });
  },

  methods: {
    postAnswer() {
      axios
        .post(`http://localhost:3005/submit`, {
          answerId: this.picked, 
          surveyId: this.currentSurveys.id 
         
        })
        .then(function(data) {
          console.log(data);
        });
    },


    isPicked: function($event) {
      this.picked = parseInt($event.target.value);
    }
  }
};
</script>


This is an example of how my axios get request is structured:

[
    {
        "id": 1,
        "survey_title": "TIC TAC Questionnaire",
        "client_name": "TIC TAC",
        "creation_date": "2020-03-30",
        "company": {
            "companyId": 1,
            "company_type": "SME",
            "models": [
                {
                    "modelId": 1,
                    "model_title": "SME Questionnaire",
                    "topics": [
                        {
                            "topicId": 1,
                            "topic_title": "Information Systems Security",
                            "topic_max_quote": 36,
                            "questions": [
                                {
                                    "questionId": 1,
                                    "question_title": "Have you ever conducted a security audit of your company's information system by an external firm?",
                                    "comments": "Security audits help identify potential threats and address them promptly. An external firm should conduct the audit for unbiased results.",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Unknown",
                                            "answer_quote": 0,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "No",
                                            "answer_quote": 1,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 3,
                                            "answer_title": "Once",
                                            "answer_quote": 2,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 4,
                                            "answer_title": "Recently",
                                            "answer_quote": 3,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 5,
                                            "answer_title": "Regularly",
                                            "answer_quote": 5,
                                            "selected": 0
                                        }
                                    ]
                                },
                                {
                                    "questionId": 2,
                                    "question_title": "Have you created an inventory of OS & Software installed on your fixed and portable hardware devices?",
                                    "comments": "Knowing the software installed on computers and machines helps prevent unauthorized installations and expiration of licenses.",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Unknown",
                                            "answer_quote": 0,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "No",
                                            "answer_quote": 1,
                                            "selected": 0
                                        },
                                        ...
                                    ]
                                },


                            ]
                        },
                        ...
                    ]
                }
            ]
        }
    }
]

Thank you

Answer №1

It is important to use distinctive names for variables within nested loops. Instead of naming them all as currentSurvey, consider using a more descriptive approach like the following:

v-for="(currentSurvey, index) in currentSurveys"

v-for="(surveyModel, index) in currentSurvey.models"

v-for="(surveyTopic, index) in surveyModel.topics"

v-for="(surveyQuestion, index) in surveyTopic.questions"

v-for="(surveyAnswer, index) in surveyQuestion.answers"

By adopting this naming convention, you will be able to effectively access and manage properties related to currentSurvey, surveyModel, surveyTopic, and surveyQuestion.

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

"Using JavaScript to find and manipulate objects within an array by either removing them or adding

I'm struggling to manipulate an array by either removing or adding an object based on its existence. I've attempted using both a for if loop and forEach loop but haven't been successful. Here's my current approach: // Object in ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

What does the `Class<Component>` represent in JavaScript?

Apologies for the lackluster title (I struggled to think of a better one). I'm currently analyzing some Vue code, and I stumbled upon this: export function initMixin (Vue: Class<Component>) { // ... } What exactly does Class<Component> ...

Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), on ...

Guide to implementing controllers in vuejs2

Hey there, I recently started using vuejs2 with a project that is based on laravel backend. In my vuejs2 project, I wrote the following code in the file routes.js export default new VueRouter({ routes: [{ path: '/test', component: ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

Tips for generating a node for the activator attribute within Vuetify?

Vuetify offers the 'activator' prop in multiple components like 'v-menu' and 'v-dialog', but there is limited information on how to create a node for it to function correctly. The documentation states: Designate a custom act ...

Is there a way for me to retrieve props that have been passed through the Vue router within a Vue component?

I have configured a route as shown below: { path: 'fit-details', name: 'fit-details', component: Fitment, props: true }, I am passing props via the route using data from the state: this.$router.push({ path: 'fit-details&a ...

How can we efficiently trigger a function that sends an axios request by leveraging data from a v-for loop?

Currently, I am developing an e-commerce platform using Rails and VueJS. In order to display the orders of a specific user, I have created a component file. Within this component, I am utilizing a v-for loop to iterate over and showcase all the information ...

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

How can we set up a Vue.js component before incorporating it into a template?

Currently, I am working on a Vue single file template where I need to fetch some data (a JWT token) and then use that token to make another request to a graphql endpoint. The Provider Component in my template requires the JWT Token to be set up with the ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

The pie chart fails to fully display

Check out the repro example I made here. The legend is displaying properly, but the graph is not showing up. What could be causing this unexpected issue? ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

Ways to discreetly conceal forward and backward buttons in the v-pagination component of Vuetify

Is there a way to remove the previous and next buttons from v-pagination in Vuetify? Here's my code snippet- <v-pagination v-model="page" :length="pageCount" :total-visible="8" color="primary" /> ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

What is the best way to incorporate this into a Vue project?

I am in the process of transitioning my code to Vue.js, so I am relatively new to Vue. In the screenshot provided (linked below), you can see that there are 4 columns inside a div with the class name columns. I attempted to use the index, like v-if='i ...