LoginSignup
3
2

More than 3 years have passed since last update.

VeeValidateでのバリデーションとSubmitボタン制御について

Posted at

VeeValidate を使ってバリデーションをしていくにあたり以下の2点で悩んだのでちょっと書いておきます。

  • 全パラメータがバリデーションOKになるまでSubmitボタンを押せなくする
  • Submitボタンを押したら2重クリック防止のためにボタンをロック(とか)する

後者はあまりVeeValidateとは関係のない話ですが、ついでです。

全パラメータがバリデーションOKになるまでSubmitボタンを押せなくする

<template>
<!-- なんかいろいろなフォーム定義 -->
  <span>
    <div v-if="displayButtons" class="field is-grouped">
      <div class="control">
        <button
          class="button is-info"
          :disabled="errors.any() || !isFormCompleted"
          @click="submitSomething"
        >
          Submit
        </button>
      </div>
    </div>
    <div v-else>
      <loading-for-submit /> <!-- ここは後で説明 -->
    </div>
  </span>

</template>

<script>
import LoadingForSubmit from '~/components/LoadingForSubmit'

export default {
  components: {
    LoadingForSubmit, // <-- ここは後で説明
  },
  data() {
    return {
      displayButtons: true,
    }
  },
  computed: {
    isFormCompleted: function() {
      if (
        !this.model.param1 ||
        !this.model.param2 ||
        !this.model.param3
      ) {
        return false
      }
      return true
    },
  },
  methods: {
    submitSomething: async function() {
      this.displayButtons = false
      // あとはなにかここで処理
      // 画面を遷移しないなら最後にthis.displayButtonsをtrueに戻しておく
    },
  },
}
</script>

骨子は、

  • isFormCompleted で、フォームの入力が完了しているかどうかを判断する
  • errors.any() で、フォームのバリデーションNGな状況がないかを判断する

の2点。

Submitボタンを押したら2重クリック防止のためにボタンをロック(とか)する

こちらはVeeValidateとは直接関係がないのですが、自分はこんな感じにしてます。

まず上記のコード内で出てきた、LoadingForSubmit というのがこんなコンポーネントになってます。

Bulma.js使ってるんでprogressとかのタグはそちらをご参照ください。

<template>
  <div class="fa-1x">
    Sending ...
    <progress class="progress is-large is-link" max="50">60%</progress>
  </div>
</template>

このコンポーネントはプログレスバーが永遠に左から右に動き続けるという動作をするだけなんですが、その表示を v-if="displayButtons" で切り替えているだけです。

  • Submit前;displayButtons = false なのでSubmitボタンが表示されている
  • Submit直後:displayButtons = true にすることで、v-ifが反転してボタンが表示されなくなり、代わりにプログレスバーが表示される

こちらは :disabled とかするだけでもいいと思います。

というか、直接関係ない内容ではあるのですが、同時に考えたくなりそうな内容だったので1つ目の話題の近くにおいてみました。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2