はじめに
vuexをいじっていく上でAPIをいじってstoreに格納する物が多い時、または多くなりそうな時
可読性、拡張性の点からstore/index.jsにごちゃごちゃ書くのではなくstoreごとに別ファイルにしよう
ただ、そのまま思うように書いていったらいろいろつまずいたので、今つまずいた!って人に読んでもらいたい。
モジュールで分割する時詰まったこと
- mutationが読み込めない
- actionが読み込めない
- gettersがうまくstateを取れなくてundefinedになってしまう
上記3つを修正する
mutation、actionが読み込めない
思うように書いて行ったらこの2つがエラーメッセージが出てきた
[vuex] unknown mutation type: (mutation名)
[vuex] unknown action type: (action名)
これの原因のコードは
actionを動かすコードにあり!! (this.commit, this.dispatch)
vue.js
- this.commit('mutation名')
+ this.commit('module名/mutation名', Response)
- this.$store.dispatch("action名");
+ this.$store.dispatch("action名/mutation名");
module名も必要みたい
これでmutation,actionは読み込める!
gettersでうまくstateを取れなくてundefinedになってしまう
問題はここ
vue.js
computed: {
変数名() {
- return this.$store.getters.getters名;
+ return this.$store.getters["module名/getter名"];
}
}
少し見たことない書き方だったので見たときこれでできるのかと思ったけどこれでいいみたい
これで解決。
ちなみに、
getterを書く所はcomputedにしよう
dataプロパティは値を変化することができるデータ。処理上変化されている場合がある。
computedプロパティはsetterがない場合、read onlyになるため変更の可能性を考慮せずに済む。
stateを変化できるのはmutationだけっていうルールを守ろうってハナシ!!