LoginSignup
3
3

More than 5 years have passed since last update.

[Vuex] vuexの配列をinputとbindするサンプル

Posted at

はじめに

少し悩んだのでメモがてら。
まとめますと、

  1. inputのイベントをキャッチして、
  2. どの位置のデータかを特定する情報を渡して、
  3. commitします。

です。

状況

以下のようなvuexを...

vuexのstate
state: {
    rows: [
        {
            id: 1,
            name: "6-1",
            score: 1,
        },
        {
            id: 2,
            name: "6-2",
            score: 1,
        }, 
        ....
    ]
}

以下のようなUIにbindする方法です。
image.png

本題

このUIは以下のようなテンプレートになっています。

vueのテンプレート
    <tbody>
      <tr 
        v-for="row in $store.getters['rows']" 
        v-bind:key="row.id">
        <td class="tdname">
        {{ row.name }}
        </td>
        <td class="tdscore">
          <input 
            type="number" 
            :value="row.score" 
            @change="(e) => { changeScore(e, row.id); }">
        </td>
      </tr>
    </tbody>

:valueはvuexの配列情報とbindします。そして、@changeで、変更をキャッチして、イベントのオブジェクトと、該当するidをイベントハンドラに渡します。

そしてイベントハンドラでcommitを呼べば…

changeのイベントハンドラ(vueのcomponentのメソッド)
methods: {
  changeScore: (e, rowid) => {
    const score = e.target.value;
    this.$store.commit("storescore", {
        score: score,
        rowid: rowid,
    });
  },
}

最後にcommitに対応するvuexのmutation(と、ついでテンプレートで使ったgetter)。

vuexのcommitとgetter
mutations : {
    storescore: (state, payload) => {
        const idx = state.rows.findIndex((ele) => {
            return ele.id == payload.rowid;
        });
        state.rows[idx].score = payload.score;
    },
},
getters : {
    rows: (state) => {
        return state.rows;
    },
}

おわりに

何かひと手間かかるというか…便利な構文を見落としているのでしょうか?それともvuexの配列をbindするという案がそもそもイマイチ?

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