LoginSignup
47
36

More than 5 years have passed since last update.

Vue.jsで処理中はボタンを無効にする

Last updated at Posted at 2018-10-10

概要

処理を開始したら、二重処理を防ぐため、ボタンが押せないようにしたかったので調べた内容をメモしておく。

実装方法

調べたら、「v-bind:disabled」で動的に無効にしたり、有効に戻したりするのが楽そう♪。

<button v-bind:disabled="isProcessing" @click="submit">何かしら処理する</button>

ただし、このためのコードを各コンポーネントに記述すると非効率なので、mixinを使って共通処理しようと思う。

実装したコード

ファイル構成は以下の2つとなりました。

ファイル構成
├ components
│  └ Register.vue
└ mixins
   └ processing.js

まず、mixinで共通処理化する。

mixins/processing.js
export default {
  data() {
    return {
      processing: false
    }
  },
  methods: {
    startProcessing: function () {
      this.processing = true
    },
    endProcessing: function () {
      this.processing = false
    },
    isProcessing: function () {
      return this.processing
    }
  }
}

コンポーネント側で利用する。

components/Register.vue
<template>
  <div>
    <button v-bind:disabled="isProcessing()" @click="submit">何かしら処理する</button>
    <p>※押すと2秒間ロックされます</p>
  </div>
</template>

<script>
import Processing from '@/mixin/processing'

export default {
  mixins: [Processing],
  name: 'articleRegister',
  methods: {
    submit: function () {
      // ボタンのロックを開始する
      this.startProcessing()

      // 何かしらの処理...

      // 2秒待つのは、Ajaxなどの処理を擬似的に表現しています
      setTimeout(function () {
        // ボタンのロックを解除する
        this.endProcessing()
      }.bind(this), 2000)
    }
  }
}
</script>

テスト

ボタンを押すと2秒間ボタンが無効になりました。
test.png

まとめ

今回はmixinで実装したが、コンポーネントのメソッドとして追加されるのでプラグインなどにして、thisとは分離したいですね。
あと、処理に時間がかかる場合、「処理中...」などのnowloadingみたいな表示を共通処理に盛り込めたら全ページで共通に使えて便利かも。

参考サイト

47
36
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
47
36