LoginSignup
8
8

More than 5 years have passed since last update.

フォームが多くなってVuexがだるくなる問題 その2

Posted at

前回書いたフォームが多くなってVuexがだるくなる問題の続編。前回より、もうちょっとコード量を減らして構造を汎用性が高いものにしてみる。

前回ゴール

  • mutationsを減らす
  • get, setを減らす
  • Vuex wayを守る
  • vue-devtoolsを手放さない

今回の追加ゴール

  • もっとコード量を減らす
  • 入力データはネストされたObjectに保存

GitHub: renowan/vuex-form-approach
Demo

対象となるstore

{
  "profile": {         // データグループ: profile
    "name": "",            // 入力field: name
    "age": 1               // 入力field: age
  },
  "info": {           // データグループ:info
    "graduated": "",      // 入力field: graduated
    "phoneNum": ""        // 入力field: phoneNum
  },
  "disabled": false   // 保存ボタン活性状態
}

ポイント1 storeへのパスをfromの更新イベントに書く

<input
type="text"
class="form-control input-sm"
placeholder=""
:value="myStore.profile.name"  
@input="inputUpdate($event.target.value, 'profile.name')">

フォーム更新イベント inputUpdate にアクセスしたい階層へのパスを書く profile.name

ポイント2 from valueとstoreへのパスをcommitする

// vue component methods
inputUpdate (value, path) {
  this.$store.commit('form2/INPUT_UPDATE', {value, path})
}

ポイント3 パスを使ってネストされた階層へアクセス

// mutations
[INPUT_UPDATE] (state, payload) {
  // パスをオブジェクトにアクセスするキーへ変換する
  const segments = payload.path.split('.')
  state[segments[0]][segments[1]] = payload.value
}

これでフォームが増えても mutations 一つで済む

今回データは2階層目に限定する書き方してるが、再帰処理で foo.bar.hoge のように書き込む階層が可変にもできるが今回はそこを割愛する。

おまけ - バリデーションの実装へ応用

説明は省略するのでこの辺を参照してください。
https://github.com/renowan/vuex-form-approach/tree/master/src/pages/form3
https://github.com/renowan/vuex-form-approach/blob/master/src/store/modules/form3.js

8
8
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
8
8