Nuxt.jsでstore/counter.jsを作り、vuexモジュールモードの勉強をしています。
store/counter.js
javascript
1export const state = () =>({ 2 count: 0, 3 name: "test" 4}) 5 6export const mutations = { 7 add(state){ 8 state.count +=1 9 }, 10 hiku(state){ 11 state.count -=1 12 } 13}
pages/users/index.vue
Javascript
1export default { 2 computed:{ 3 count(){ 4 return this.$store.state.counter.count 5 }, 6 name(){ 7 return this.$store.state.counter.name 8 } 9 }, 10 methods:{ 11 addCount(){ 12 this.$store.commit("counter/add") 13 }, 14 hikuCount(){ 15 this.$store.commit("counter/hiku") 16 } 17 } 18}
これで問題なく表示はできたのですが、さらに簡潔にかけるmapState、mapMutationsというヘルパーを知ったのですが、
Javascriot
1computed: mapState({ 2 count: state => state.counter.count, 3 name: state => state.counter.name 4}), 5methods:{ 6 addCount(){ 7 this.$store.commit("counter/add") 8 }, 9 hikuCount(){ 10 this.$store.commit("counter/hiku") 11 } 12}
いまいち便利というか簡潔という感じがしないのですが、もっと効率良い書き方などあるのでしょうか?また、あえてmapStateを使用する利点など教えていただけると助かります。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/08 05:52