【Vue.js】mapヘルパーの使い方まとめ
はじめに
Vuexのmapヘルパーについて、使い方をまとめます。
mapヘルパーに関する記事はいくつかあります。
しかし、引数を渡したり、jsファイルをモジュールに分割している場合の記述方法について、確りまとめられた記事がなかったため、本記事を作成しています。
mapヘルパーを使用するメリット
mapヘルパーを使用することにより、コードがすっきりとして可読性が向上し、効率の良い記述が可能です。
mapヘルパーは4種類存在します。
①mapState
②mapGetters
③mapMutations
④mapActions
この内、①mapState、③mapMutationsは下記の理由により、使用することはあまりないかと思います。
①mapState・・・stateを直接参照することは非推奨である。あまり使用するべきではない。
③mapMutations・・・mutationsはactionsから呼び出すのが望ましい。
mapActions
「index.js」のactions内の関数を呼び出す。
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions(["increment", "incrementBy"]),
},
};
「hoge.js」のactions内の関数を呼び出す。
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions('hoge', ["increment", "incrementBy"]),
...mapActions(['decrement'])//index.jsのactionsを呼び出す。
...mapActions('hoge/hoge', ['decreamentBy'),//hogeディレクトリのhoge.jsのactionsを呼び出す。
},
};
「hoge.js」のactions内の関数に引数を渡す。
※関数名に注意!
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions("hoge", ["incrementActions", "incrementByActions"]),
increament() {
this.increamentActions(引数);
},
//オブジェクトも渡せる
incrementBy() {
this.incrementByActions({
a:1
b:2
})
}
},
};
mapGetters
「index.js」のgettersの値を参照する。
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
}
「hoge.js」のgettersの値を参照する。
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters('hoge', [
'doneTodosCount',
'anotherGetter',
]),
...mapGetters('hoge', ['notDoneTodosCount'])//hoge.jsのgettersを参照
...mapGetters('hoge/hoge', ['hogeGetter'])//hogeディレクトリのhoge.jsのgettersを参照
}
}
メリット
mapヘルパーを使っていて、いいな!と思ったのは、モジュールのファイル名が変更した際、一括で変更できる点です。
import { mapActions } from 'vuex'
export default {
methods: {
//...mapActions('hoge', ["increment", "incrementBy"]),
//モジュールのファイル名が「hogehoge.js」に変更すると、、
...mapActions('hogehoge', ["increment", "incrementBy"])
//モジュールのディレクトリ構造が変わっても、、
...mapActions('hoge/hoge/hoge', ["increment", "incrementBy"])
},
};
最後に
間違いを発見された方は、お手数ですがコメントにてお知らせ下さい。
Author And Source
この問題について(【Vue.js】mapヘルパーの使い方まとめ), 我々は、より多くの情報をここで見つけました https://qiita.com/kondo97/items/e059b2e96a004e94763d著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .