要件など
- フォームの内容に不備があった場合には「つぎへ」のボタンを押せなくする
- dataとinputをバインドするのではなく、computedのset,getプロパティでvuexと紐づけたやつをバリデーションしたい
つまりどころ
vuelidateを使っていたのだけど、なんだか面倒臭そう。。。
参考 : Validating computed properties returning an object #241
vee-validateなら簡単にできそう
いろいろ調べた結果、vee-validateを使えば、やりたいことがあっさりと実装できそう。
公式リファレンスに、Validating Vuex Stateという項目があるくらいなのでこっちに乗り換えました。
vee-validateの使い方
使い方に関しては、この辺りを参考にしました。
公式がめちゃくちゃ充実していてありがたい。
ボタンの実装
入力項目にエラーがある場合には、ボタンを押せなくする処理は、
Flagsのやり方で簡単に実装できました。
flagsにある項目は、自動的にfields
配下に登録されている。要件に合う条件をcomputedに記述してやればOK。
条件は以下の通り
- touched: indicates that the field has been touched or focused.
- untouched: indicates that the field has not been touched nor focused.
- dirty: indicates that the field has been manipulated.
- pristine: indicates that the field has not been manipulated.
- valid: indicates that the field has passed the validation.
- invalid: indicates that the field has failed the validation.
- pending: indicates that the field validation is in progress.
- validated: indicates that the field has been validated at least once by an > - - event or manually using validate() or validateAll().
- changed: indicates that the field value has been changed (strict check).
touchedは、フォーカスされたときに発火して、dirtyは値の入力があったときに発火って感じ。
vuelidateのtouchedとdirtyを合わせてdirty1つだったのでこの辺りも使い勝手がよさそう。
サンプルコード
vee-validate自体は、main.jsで読み込む前提で作ってみた。
InputName.Vue
<template>
<div>
<input
type="text"
name="name"
v-validate="'required|min:3'"
v-model="name"
>
<button
:disable="isDisable"
/>
</div>
</template>
<script>
export default {
computed: {
name: {
set(val) { this.$store.dispatch('setName', val) },
get() { return this.$store.getters('getName') }
}
},
isDisable() {
//
return Object.keys(this.fields).some(key => this.fields[key].invalid)
}
}
</script>