Как получить доступ к идентификатору во вложенном v-for vuejs и опубликовать с помощью axios - PullRequest
0 голосов
/ 30 апреля 2020

Я разрабатываю приложение с серверной частью в typeorm и внешним интерфейсом с vuejs js. Цель этого приложения - установить данные от клиентов благодаря опросу.

Для этого я получаю данные из моего бэкэнда с помощью запроса топора ios, и я хочу поставить отмеченные флажки с топор ios почтовый запрос. Я хочу отправить множество идентификаторов в моем запросе на топор ios, но мне не удалось их получить / я написал несколько комментариев в своем коде, надеюсь, это поможет понять мой вопрос.

<template>
  <div>
    <p>Nom du questionnaire : {{ currentSurveys.survey_title }}</p>
    <p>Type d'entreprise : {{ currentSurveys.company.company_type }}</p>

    <div>
      <!-- 1rst loop to get the datas -->
      <div v-for="(currentSurvey, index) in currentSurveys" v-bind:key="index">
        <v-row align="center">
          <v-expansion-panels :popout="popout" :tile="tile">
            <!-- 2nd loop to get the company model -->
            <v-expansion-panel
              v-for="(currentSurvey, index) in currentSurvey.models"
              v-bind:key="index"
            >
              <!-- 3rd loop to get 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>

                <!-- 4th lopp to get 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>
                    <!-- 5th loop the get the answers as checkboxes-->
                    <!--I want to use the postAnswers() functions when the checkbox is cliked and send the following datas : surveyId, modelId, topicId, questionId-->
                    <!-- I get 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>quote : {{ currentSurvey.answer_quote }}</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">Soumettre</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) //voir le fichier surveydata.json
      .then(response => {
        this.currentSurveys = response.data;
      })
      .catch(e => {
        console.log(e);
      });
  },

  //Where I need help//
  methods: {
    postAnswer() {
      axios
        .post(`http://localhost:3005/submit`, {
          answerId: this.picked, 
          surveyId: this.currentSurveys.id 
          // modelId:??
          // topicId:??
          // questionId:??

        })
        .then(function(data) {
          console.log(data);
        });
    },


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


Вот так выглядит мой топор ios запрос на получение:

[
    {
        "id": 1,
        "survey_title": "questionnaire TIC TAC",
        "client_name": "TIC TAC",
        "creation_date": "2020-03-30",
        "company": {
            "companyId": 1,
            "company_type": "TPE",
            "models": [
                {
                    "modelId": 1,
                    "model_title": "Questionnaire TPE",
                    "topics": [
                        {
                            "topicId": 1,
                            "topic_title": "Sécurité des systèmes d'informations",
                            "topic_max_quote": 36,
                            "questions": [
                                {
                                    "questionId": 1,
                                    "question_title": "Avez-vous, un jour, procédé à un audit de sécurité du système d'information de votre entreprise par une entreprise externe ?",
                                    "comments": "Des audits de sécurité permettent de détecter les éléments dangereux et les corrigés rapidement. L'audit doit être fait par une entreprise externe pour être avoir un résultat le plus neutre possible.",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu",
                                            "answer_quote": 0,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non",
                                            "answer_quote": 1,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 3,
                                            "answer_title": "Une fois",
                                            "answer_quote": 2,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 4,
                                            "answer_title": "Récemment",
                                            "answer_quote": 3,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 5,
                                            "answer_title": "Régulièrement",
                                            "answer_quote": 5,
                                            "selected": 0
                                        }
                                    ]
                                },
                                {
                                    "questionId": 2,
                                    "question_title": "Avez-vous procédé à un inventaire des OS & logiciels, installés sur le matériel fixe et portable de l'entreprise ?",
                                    "comments": "Connaître les programmes installés sur les ordinateurs et machines permet de limiter l'installation de nouveaux programmes et l'oublie de renouvellement de licences.",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu",
                                            "answer_quote": 0,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non",
                                            "answer_quote": 1,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 5,
                                            "answer_title": "Régulièrement",
                                            "answer_quote": 5,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 6,
                                            "answer_title": "Occasionnellement",
                                            "answer_quote": 3,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 11,
                                            "answer_title": "Peu",
                                            "answer_quote": 2,
                                            "selected": 0
                                        }
                                    ]
                                },


                            ]
                        },
                        {
                            "topicId": 2,
                            "topic_title": "Sécurité du réseau",
                            "topic_max_quote": 16,
                            "questions": [
                                {
                                    "questionId": 10,
                                    "question_title": "Présence d'un pare-feu ?",
                                    "comments": "Un pare-feu est un outil indispensable pour la sécurité de votre réseau. L'essentiel des menaces peut être bloqué grâce à cet outil performant. Il doit néanmoins être bien configuré pour être efficace.",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu",
                                            "answer_quote": 0,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non",
                                            "answer_quote": 1,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 18,
                                            "answer_title": "Oui mais il n'est pas mis à jour",
                                            "answer_quote": 2,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 19,
                                            "answer_title": "Oui mis à jour régulièrement",
                                            "answer_quote": 3,
                                            "selected": 0
                                        }
                                    ]
                                },
                                {
                                    "questionId": 11,
                                    "question_title": "Les appareils importants sont-ils reliés à un onduleur ?",
                                    "comments": "Les onduleurs permettent de gérer les coupures de courant et des orages. Ils assurent les fonctionnalités des appareils reliés.",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu",
                                            "answer_quote": 0,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non",
                                            "answer_quote": 1,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 20,
                                            "answer_title": "En partie",
                                            "answer_quote": 2,
                                            "selected": 0
                                        },
                                        {
                                            "answerId": 21,
                                            "answer_title": "Oui",
                                            "answer_quote": 3,
                                            "selected": 0
                                        }
                                    ]
                                },

                            ]
                        }
                    ]
                }
            ]
        }
    }
]

Спасибо

1 Ответ

1 голос
/ 30 апреля 2020

Вам нужно по-разному именовать ваши переменные во внутренних циклах. В настоящее время вы называете их как currentSurvey в каждом l oop вместо того, чтобы называть их чем-то вроде этого

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"

таким образом, вы можете получить доступ ко всем этим свойствам выше currentSurvey, surveyModel, surveyTopi c, surveyQuestion

...