State
Vue ComponentをVuex Stateへと値を取ってくる
一番シンプルなやり方はcomputedプロパティの中でStoreのStateをreturnすること
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
この場合、Storeのstateを使うcomponentで毎回storeをimportしなければならない
Vuexはすべての子コンポーネントにStoreを注入するstoreオプションを提供している
const app = new Vue({
el: '#app',
// 全ての子コンポーネントにstoreを注入する
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
// こっちでも良い
Vue.use(Vuex)
vueコンポーネント内で、this.$storeでstoreにアクセスできるようになる
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState
複数のstoreのstateのプロパティを使う場合は、冗長になるためmapStateを使う
// in full builds helpers are exposed as Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// arrow functionsを使うと短く書ける
count: state => state.count,
// 文字列の 'count' を書くのは `state => state.count`と書くのと同じ処理になる
countAlias: 'count',
// thisでローカルstateにアクセスする場合は、arrow functionではなく、nomal functionを使う
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
spread operator
Getters
GetterはcomputedのStore版っぽい
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
// GetterはStateを第一引数として受け取る
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
MapGetters
import { mapGetters } from "vuex";
export default {
// ...
computed: {
// mix the getters into computed with object spread operator
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
Getterを違う名前でマッピングしたい場合は、オブジェクトを使う
...mapGetters({
// map `this.doneCount` to `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})