проверка нескольких серверов проверки подлинности в Vue

#vue.js #vee-validate

Вопрос:

У меня есть экран ChangeInfo, состоящий из трех компонентов, соответствующих трем серверам проверки. Если все три допустимы, я установлю переменную ShowModal = true для отображения модального уведомления об успешном завершении. Но если у одного из трех есть ошибка, ShowModal будет ложным и console.log("Failed") сообщит об ошибке. Моя функция отлично работает, если все 3 допустимы, но только console.log("Failed") в первом случае, если. Это мой код, вы, ребята, можете увидеть triggerSubmit() function

 <template>
  <div class="d-block">
    <ValidationObserver ref="profile" tag="div">
      <ShowProfile
        :isUpdatedProfile="isUpdatedProfile"
        @update-profile="updateProfile"
      />
    </ValidationObserver>

    <ValidationObserver ref="workInfo" tag="div">
      <ShowWorkInfo
        :isUpdatedWorkInfo="isUpdatedWorkInfo"
        @update-work-info="updateWorkInfo"
      />
    </ValidationObserver>

    <ValidationObserver ref="personalInfo" tag="div">
      <ShowPersonalInfo
        :isUpdatedPersonalInfo="isUpdatedPersonalInfo"
        @update-personal-info="updatePersonalInfo"
      />
    </ValidationObserver>

    <div class="w--27 mw-100 mx-auto my-9">
      <button
        @click="triggerSubmit"
        v-b-modal="'modal-info'"
        class="btn btn-primary w-100"
      >
        {{ $t('common.btn.btn_update') }}
      </button>
    </div>
    <ModalInfo v-if="showModal" :infoMess="$t('common.message.updated')" />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { VeeValidateObserverRef } from '@/models/Common/Validation'
import { getModule } from 'vuex-module-decorators'
import ShowProfile from './Components/ShowProfile.vue'
import ShowWorkInfo from './Components/ShowWorkInfo.vue'
import ShowPersonalInfo from './Components/ShowPersonalInfo.vue'
import ModalInfo from '@/components/Modal/ModalInfo.vue'
import Information from '@/store/modules/Information'
import store from '@/store'
import axios from 'axios'

const InformationModule = getModule(Information, store)

@Component({
  components: {
    ShowProfile,
    ShowWorkInfo,
    ShowPersonalInfo,
    ModalInfo
  }
})
export default class ChangeInfo extends Vue {
  $refs!: {
    workInfo: VeeValidateObserverRef
    personalInfo: VeeValidateObserverRef
    profile: VeeValidateObserverRef
  }
  public isUpdatedWorkInfo: boolean = false
  public isUpdatedProfile: boolean = false
  public isUpdatedPersonalInfo: boolean = false
  private showModal: boolean = false
  public infoMess!: string

  updateProfile(profile: any) {
    axios
      .put('https://609b82962b549f00176e394f.mockapi.io/profile/1', {
        recent_situation: profile.recent_situation,
        email: profile.email,
        avatar: profile.avatar,
        last_name: profile.last_name,
        first_name: profile.first_name,
        furigana_lastname: profile.furigana_lastname,
        furigana_firstname: profile.furigana_firstname,
        self_introduction: profile.self_introduction
      })
      .then(response => {
        profile = response.data
        console.log(profile)
      })
      .catch(error => console.log(error))
    this.isUpdatedProfile = false
    profile.recent_situation = ''
    profile.email = ''
    profile.last_name = ''
    profile.first_name = ''
    profile.furigana_lastname = ''
    profile.furigana_firstname = ''
    profile.self_introduction = ''
    this.$refs.profile.reset()
  }

  updateWorkInfo(workInfo: any) {
    axios
      .put('https://609b82962b549f00176e394f.mockapi.io/work_info/1', {
        status: workInfo.status,
        company: workInfo.company,
        department: workInfo.department,
        position: workInfo.position,
        postcode: workInfo.postcode,
        prefectures: workInfo.prefectures,
        district: workInfo.district,
        address: workInfo.address,
        building: workInfo.building,
        phone_numbers: workInfo.phone_numbers,
        urls: workInfo.urls
      })
      .then(response => {
        workInfo = response.data
        console.log(workInfo)
        InformationModule.CHANGE_WORK_INFO(workInfo)
      })
      .catch(error => console.log(error))
    this.isUpdatedWorkInfo = false
    workInfo.status = false
    workInfo.company = ''
    workInfo.department = ''
    workInfo.position = ''
    workInfo.postcode = ''
    workInfo.prefectures = ''
    workInfo.district = ''
    workInfo.address = ''
    workInfo.building = ''
    workInfo.phone_numbers = [{ phone: '' }]
    workInfo.urls = [{ url: '' }]
    this.$refs.workInfo.reset()
  }

  updatePersonalInfo(personalInfo: any, gender_selected: any) {
    axios
      .put('https://609b82962b549f00176e394f.mockapi.io/personal_info/1', {
        gender: gender_selected,
        nearest_station: personalInfo.nearest_station,
        postcode: personalInfo.postcode,
        prefectures: personalInfo.prefectures,
        district: personalInfo.district,
        address: personalInfo.address,
        building: personalInfo.building,
        phone_numbers: personalInfo.phone_numbers,
        urls: personalInfo.urls
      })
      .then(response => {
        personalInfo = response.data
        console.log(personalInfo)
        InformationModule.CHANGE_PERSONAL_INFO(personalInfo)
      })
      .catch(error => console.log(error))
    this.isUpdatedPersonalInfo = false
    personalInfo.nearest_station = ''
    personalInfo.postcode = ''
    personalInfo.prefectures = ''
    personalInfo.district = ''
    personalInfo.address = ''
    personalInfo.building = ''
    personalInfo.phone_numbers = [{ phone: '' }]
    personalInfo.urls = [{ url: '' }]
    this.$refs.personalInfo.reset()
  }

  triggerSubmit() {
    this.$refs.profile.validate().then(isValidate => {
      if (isValidate) {
        this.$refs.workInfo.validate().then(isValidate => {
          if (isValidate) {
            this.$refs.personalInfo.validate().then(isValidate => {
              if (isValidate) {
                this.showModal = true
                this.isUpdatedWorkInfo = true
                this.isUpdatedPersonalInfo = true
                this.isUpdatedProfile = true
              }
            })
          }
        })
      } else {
        console.log('Failed')
      }
    })
    this.showModal = false
  }
}
</script>
 

Кроме того, есть ли лучший способ написать эту функцию?

Ответ №1:

используйте асинхронное/ожидание

 checkProfile(){
  return this.$refs.profile.validate()
},
checkWorkInfo(){
  return this.$refs.workInfo.validate()
},
checkPersonalInfo(){
  return this.$refs.personalInfo.validate()
},
async triggerSubmit() {
 const profileValidate = await checkProfile()
 const workInfoValidate = await checkWorkInfo()
 const personalInfoValidate = await checkPersonalInfo()
 if(profileValidate amp;amp; workInfoValidate amp;amp; personalInfoValidate)
  this.showModal = true
 else {
  this.showModal = false
  console.log("Failed")
 }
}
 

Комментарии:

1. Ладно, я получил твой ответ. Я просто выясняю, что могу обернуть 3 наблюдателя проверки внутри 1 наблюдателя проверки, тогда я смогу проверить это. Он будет включать в себя 3 наблюдателя проверки внутри, он похож на ваш anwser.