programing

Vuex 3 계산 속성을 사용한 Vee 4 검증

goodcopy 2022. 7. 12. 22:31
반응형

Vuex 3 계산 속성을 사용한 Vee 4 검증

공식 Vee-Validate 가이드에 따라 다단계 양식 마법사를 작성하려고 합니다.이 가이드의 예는 다음과 같습니다.이것은 도움이 됩니다만, Vuex를 여기에 짜넣고 싶습니다.Vee-Validate의 디폴트가 아닌 커스텀 컴포넌트를 사용하고 있습니다.<Form/>그리고.<ErrorMessage/>구성 요소들.커스텀 컴포넌트는 Vee-Validate 기본 컴포넌트를 내부적으로 사용하지 않습니다.

하지만 이렇게 하는 것은 나에게 몇 가지 문제를 가져왔다.현재 문제는 Vuex 상태를 반응적으로 Vee-Validate로 전환하는 방법을 찾을 수 없다는 것입니다.

주요 컴포넌트의 텍스트 입력은 다음과 같이 사용됩니다.

    <text-input
        label="Name"
        name="name"
        v-model="name"
    />
    ...
computed: {
  ...mapGetters({
      businessFields: 'business/businessFields',
  }),
  name: {
      get () {
          return this.businessFields.name;
      },
      set (value) {
          this.$store.commit('business/setName', value)
      }
  },
},

이는 모두 Vuex가 여기서 제공하는 양방향 계산 속성 가이드에 따른 것입니다.

이 필드를 앞서 링크된 Vee-Validate 다중 양식 마법사에 통합하려고 합니다.기본적으로 로컬 값이 아닌 Vuex를 리셋하고 오가며 값을 가져오도록 변경했습니다.다음과 같은 경우:

<!-- FormWizard.vue (from the Vee-Validate example adapted to use Vuex) -->
<template>
  <form @submit="onSubmit">
    <slot />

    <div>
      <button v-if="hasPrevious" type="button" @click="goToPrev">
        Previous
      </button>
      <button type="submit">{{ isLastStep ? "Submit" : "Next" }}</button>
    </div>
  </form>
</template>

<script>
import { useForm } from "vee-validate";
import { useStore } from 'vuex';
import { ref, computed, provide } from "vue";

export default {
  name: "FormWizard",
  emits: ["next", "submit"],
  props: {
    validationSchema: {
      type: null,
      required: true,
    },
    formDataGetter: {
      type: String,
      required: true,
    }
  },
  setup(props, { emit }) {
    const store = useStore();
    const currentStepIdx = ref(0);

    // Injects the starting step, child <form-steps> will use this to generate their ids
    const stepCounter = ref(0);
    provide("STEP_COUNTER", stepCounter);
    // Inject the live ref of the current index to child components
    // will be used to toggle each form-step visibility
    provide("CURRENT_STEP_INDEX", currentStepIdx);

    // if this is the last step
    const isLastStep = computed(() => {
      return currentStepIdx.value === stepCounter.value - 1;
    });

    // If the `previous` button should appear
    const hasPrevious = computed(() => {
      return currentStepIdx.value > 0;
    });

    const { resetForm, handleSubmit } = useForm({
      validationSchema: props.validationSchema,
    });

    // We are using the "submit" handler to progress to next steps
    // and to submit the form if its the last step
    // parent can opt to listen to either events if interested
    const onSubmit = handleSubmit(() => {
      // Sets initial values for the values already filled
      // effectively fills the inputs when clicking on "previous"
      resetForm({
        values: {
          ...store.getters[props.formDataGetter]
        },
      });
      if (!isLastStep.value) {
        currentStepIdx.value++;
        emit("next", store.getters[props.formDataGetter]);

        return;
      }

      emit("submit");
    });

    function goToPrev() {
      if (currentStepIdx.value === 0) {
        return;
      }

      currentStepIdx.value--;
    }

    return {
      onSubmit,
      hasPrevious,
      isLastStep,
      goToPrev,
    };
  },
};
</script>

FormStep.vue스텝은 완전히 동일합니다.FormWizard를 이렇게 사용할 경우:

  <form-wizard :validationSchema="validationSchema" @submit="onSubmit" formDataGetter="setup/setupFields">
    <form-step>
      <business-form></business-form>
    </form-step>
  </form-wizard>

를 사용하여setup()다음과 같이 FormWizard를 내장한 주요 컴포넌트:

  setup() {
    const store = useStore();
    // You don't have to validate each step
    // vee-validate will only validate the fields rendered from the schema
    // fields not rendered errors will be ignored, so it all just works!
    const validationSchema = yup.object().shape({
      name: yup.string().required(),
    });

    /**
     * Only Called when the last step is submitted
     */
    const onSubmit = (values) => {
      console.log(values);
      alert(store.getters['business/businessFields'].name);
    };

    return {
      validationSchema,
      onSubmit,
    };
  },

문제는 다음 페이지로 넘어가면 이름이 필요하다는 검증 오류가 뜬다는 것입니다.이는 Vee-Validate를 사용하지 않기 때문입니다.useField()내 밭을 수용하는 기능을 합니다. useField()로 링크할 필요가 있는 계산 속성을 반환합니다.v-model를 참조해 주세요.여기서 발생하는 문제는 Vuex 필드를 사용할 때 변경할 수 없다는 것입니다.useField()를 변경할 수 없습니다.useFieldVuex의 계산된 속성은 Vee-Validate의 옵션이 아니기 때문에 Vuex의 계산 속성은 Vue-Validate의 옵션이 아닙니다.

Vuex 스토어와 Vee-Validate를 모두 갱신할 수 있는 방법으로 Vee-Validate 3과 Vuex 4를 구현하려면 어떻게 해야 합니까?useForm()계산 속성이 하나만 있는 필드?

아니면 다른 접근법이 있을까요?

언급URL : https://stackoverflow.com/questions/66844224/vee-validate-4-validation-with-vuex-3-computed-property

반응형