vuex2.xその0002 mapStateのこと
参考にさせて頂いたページ
はじめに
storeを複数使うような規模のものを書いていないのでmapStateはまだ自分には必要なさそうですが、少し書いてみました。
サンプルソースコード
こんな感じかなー。と書いてみました。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="">
</head>
<body>
<div id="app">
</div>
<script src="js/vue.js"></script>
<script src="js/vuex.js"></script>
<script>
const mapState = Vuex.mapState;
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: function(state){
return state.count++;
},
decrement: function(state){
return state.count--;
}
}
});
const Counter = {
template: `
<div>
<div>{{ count }}</div>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
`,
computed: mapState({
// アロー関数は、コードをとても簡潔にできます!
count: state => state.count,
// 文字列を渡すことは、`state => state.count` と同じです
countAlias: 'count',
// `this` からローカルステートを参照するときは、通常の関数を使わなければいけません
countPlusLocalState (state) {
return state.count + this.localCount
}
}),
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
}
};
const app = new Vue({
el: '#app',
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
});
</script>
</body>
</html>
このコードについて
上記のサンプルでは、公式ドキュメントにあったオブジェクトスプレッド演算子は使っていませんが、ローカルなcomputedも定義する場合はそのような記述が必要になるようです。
オブジェクトスプレッド演算子が使えない環境下では、Object.assign()とかlodashの_.assign()とか使う感じでしょうか。