Заполнение формы значениями из базы данных в форме, опосредованной Vuejs - Vuelidate - axios - PullRequest
0 голосов
/ 11 апреля 2019

У меня проблемы с заполнением элементов формы данными, полученными из базы данных.

Моя форма "разбита" на несколько компонентов (ниже я показал только один из них - Gap3CropInfo).Когда загружается страница «материнской» формы - Gap3Form, она извлекает данные (если они есть), которые ранее были введены пользователем.

Моя проблема в том, что, хотя я могу заполнить массив форм этими значениями, я не знаю, как заставить их отображаться в самих элементах формы.

Vuelidate используется для проверки формы.

Любое направление будет оценено.

Спасибо, Том

Gap3Form

<template>
  <v-content>
    <v-container fluid fill-height>
      <v-layout justify-center>
        <v-flex xs12 sm6>
          <h1>Production and sale of produce</h1>
            <v-card flat>
              <div v-if="isIn">
                <div v-if="wizardInProgress">
                  <keep-alive>
                    <component
                      ref="currentStep"
                      :is="currentStep"
                      @update="processStep"
                      :wizard-data="form"
                    ></component>
                  </keep-alive>
                  <div class="progress-bar">
                    <div :style="`width: ${progress}%;`"></div>
                  </div>

                  <!-- Actions -->
                  <div class="buttons" style="padding-right:0.4rem;padding-bottom:1rem;">
                    <button
                      @click="goBack"
                      v-if="currentStepNumber > 1"
                      class="btn-outlined"
                    >Back
                    </button>
                    <button
                      @click="nextButtonAction"
                      :disabled="!canGoNext"
                      class="btn"
                    >{{isLastStep ? 'Process all this information' : 'Next'}}</button>
                  </div>
                  <logout-button></logout-button>
                </div>
                <div v-else>
                  <v-alert
                    v-if="isDone"
                    :value="true"
                    type="success"
                    transition="scale-transition"
                    dismissible
                  >
                    {{message}}
                  </v-alert>
                  <p>Thank you for completing the form.</p>

                </div>
              </div>
              <pre><code>{{form}}
импорт Gap3CropInfo из. ./Gap3CropInfo импорт Gap3CropList из ./Gap3CropList импорт Gap3Fertilizers из../Gap3SaleInfo 'импортировать LogoutButton из' ./LogoutButton 'экспортировать по умолчанию {компоненты: {Gap3CropInfo, Gap3Fertilizers, Gap3Pesticides, Gap3HarvestInfo, Gap3SaleInfo, LogoutButton}, data () {return {currentStepNumber: 1. Route.me: 1. $.id, lang: this. $ i18n.locale, canGoNext: false, isDone: false, wizardData: {}, сообщение: '', alert: true, шаги: ['Gap3CropInfo', 'Gap3Fertilizers', 'Gap3Pesticides', 'Gap3HarvestInfo',' Gap3SaleInfo ',], форма: {product: null, источник: null, area: null, startdate: null, fertname1: null, fertquant1: null, fertdate1: null, agchemname1: null, agchemquant1: null, agchemdate1: null, yield: null, обработка: null, saledate: null, покупатель: null, количество продано: null,}}}, созданный () {this.loadForm (this.gapid, this.lang);}, вычисляется: {isIn: function () {вернуть this. $ store.getters.isLoggedIn}, isLastStep () {вернуть this.currentStepNumber === this.length}, wizardInProgress () {вернуть this.currentStepNumber <= this.length}, length () {вернуть this.steps.length}, currentStep () {вернуть this.steps [this.currentStepNumber - 1]}, progress () {вернуть this.currentStepNumber / this.length * 100}}, методы: {loadForm (gapid, lang) {var vm = this;axios.get ('/ cropdata /' + gapid) .then (function (resp) {vm.cards = resp.data; var z = vm.cards [0] .product.length; if (z === 0){vm.bNoRecords = true;} else {vm.bNoRecords = false; vm.form.product = vm.cards [0] .product; vm.form.source = vm.cards [0] .source; vm.form.area = vm.cards [0] .area; vm.form.startdate = vm.cards [0] .startdate; //vm.$set(vm.wizardData,'product',vm.cards[0].product)//vm.Object.assign('product ', vm.cards [0] .product);}}) .catch (function (resp) {console.log ("Что-то пошло не так!"); vm.bNoRecords = true;});}, nextButtonAction () {if (this.isLastStep) {this.submitCrop ()} else {this.goNext ()}}, processStep (step) {Object.assign (this.form, step.data);this.canGoNext = step.valid}, goBack () {this.currentStepNumber--;this.canGoNext = true;}, goNext () {this.currentStepNumber ++;this. $ nextTick (() => {this.canGoNext =! this. $ refs.currentStep. $ v. $ invalid})}}}

Gap3CropInfo

<template>
  <div class="formdiv">
      <h3 class="title">Section 1. Crop information</h3>
      <form @input="submit" class="form">
      <v-card-text>
        <v-text-field
            v-model.trim="$v.form.product.$model"
            type="text"
            label="Name of produce/seeds"
            id="product"
            required
            autofocus
        ></v-text-field>
        <v-text-field
            v-model="$v.form.source.$model"
            type="text"
            label="Code: plot/section/farm/farmholder"
            id="source"
            required
        ></v-text-field>
        <v-text-field
            v-model="$v.form.area.$model"
            type="text"
            label="Area of production"
            required
            id="area"
        ></v-text-field>
        <v-text-field
            v-model="$v.form.startdate.$model"
            type="date"
            label="Date of sowing/transplanting"
            required
            id="startdate"
        ></v-text-field>
      </v-card-text>
      </form>
    </div>
</template>

<script>
  import {required} from 'vuelidate/lib/validators'

  export default {
    props: {
      wizardData: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        form: {
          product: null,
          source: null,
          area: null,
          startdate: null,
        }
      }
    },
    validations: {
      form: {
        product: {
          required
        },
        source: {
          required
        },
        area: {
          required
        },
        startdate: {
          required
        }
      }
    },
    methods: {
      submit () {
        this.$emit('update', {
          data: {
            product: this.form.product,
            source: this.form.source,
            area: this.form.area,
            startdate: this.form.startdate,
          },
          valid: !this.$v.$invalid
        })
      },
    }
  }
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...