LoginSignup
32
34

More than 3 years have passed since last update.

Vuex Storeへのアクセス書き方まとめ

Last updated at Posted at 2019-08-21

storeへのアクセス

// Componentから
this.$store

// それ以外
import store from 'path/to/store.js';
store

export default new Vuex.Store()してるファイルを読み込む。
Storeを別ファイルにしていない時はComponent以外からのアクセスはできない(と思う)。

state

// 基本形
this.$store.state.value;

// namespaceが設定されてるやつ
this.$store.state.namespaceName.value;

// contextからだと、namespaceに属するもののみになる
context.state.value;

// contextからルートのstateにアクセス
context.rootState.value

getters

this.$store.getters.doneTodos;

//namespaceが設定されてるやつ
this.$store.getters['namespaceName/doneTodos'];

contextでも同様。

mutations

this.$store.commit('mutationName');

this.$store.commit('namespaceName/mutationName');

contextでも同様。

actions

this.$store.dispatch('actionName');

this.$store.dispatch('namespaceName/actionName');

これもcontextでも変わらず
dispatch()はPromiseを返すのでthen()とかawaitできます。

mapGetters()

...はスプレッド構文。配列を展開して列挙してくれる。

// ルートに記述しているgetters
computed: {
    ...mapGetters(['doneTodos']),
}

// モジュール化してるやつ
computed: {
    ...mapGetters('namespaceName', ['doneTodos']),
}

mapState()

こちらもmapGetters()と同じように使える。

computed: {
    ...mapState(['state'])
}
computed: {
    ...mapState('namespace', [
        'state',
    ])
}


computed: {
    ...mapState('namespace', [
        'state',
    ])
}

32
34
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
32
34