Vuexとは
コンポーネント間でデータを共有するため状態管理ライブラリ
いわゆる、グローバル変数のようなものを定義し操作できる
使い方
これ以降、VueCLIで作成を想定して記載
1. Vuexのインストール
Vuexのインストール
$ npm install vuex
2. /src
直下にstore.js
を作成
このへんの場所に関してはプロジェクトに応じて設定する
図. 今回のプロジェクトのディレクトリ構成
3. main.js
のVueインスタンスにVuexを登録
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store' // 追加行
Vue.config.productionTip = false
new Vue({
store, // 追加行
render: h => h(App),
}).$mount('#app')
4. store.js
およびVueコンポーネントを実装
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// Vuexインスタンス生成
export default new Vuex.Store({
// state: Vuexで管理する状態を定義
state: {
count: 0, // 1
name: 'MouMou',
password: 'hoge'
},
// getters : stateの値を取得する処理を定義
// 引数のstateは上で宣言した状態管理オブジェクト
getters: {
count: state => state.count, // 2
name: state => state.name, // 3
password: state => state.password, // 3
},
// mutations : stateの値を変更する処理を定義
// 引数のstateは上で宣言した状態管理オブジェクト
// 非同期処理に対応していない
mutations: {
setCount(state, newCount) { // 4
state.count = newCount
},
setName(state, newName) { // 5
state.name = newName
},
setPassword(state, newPassword) { // 5
state.password = newPassword
}
},
// actions : mutationを呼び出す処理を定義
// 非同期も対応している
actions: {
setCountAction({ commit }, newCount) { // 6
commit('setCount', newCount)
},
setNameAction({ commit }, newName) { // 7
commit('setName', newName)
},
setPasswordAction({ commit }, newPassword) { // 7
commit('setPassword', newPassword)
},
}
})
App.vue (他コンポーネントでも同様に記載できる)
<template>
<div id="app">
<!-- state -->
<p>1. count = {{countDirect}}</p>
<!-- getters -->
<p>2. count = {{count}}</p>
<p>3. name = {{name}}</p>
<p>3. password = {{password}}</p>
<!-- mutations -->
<p><button @click="setCount">4. count = {{count}}</button></p>
<p><button @click="setName('Qiita')">5. name = {{name}}</button></p>
<p><button @click="setPassword('huga')">5. password = {{password}}</button></p>
<!-- actions -->
<p><button @click="setCountAction">6. count = {{count}}</button></p>
<p><button @click="setNameAction('Vuex')">7. name = {{name}}</button></p>
<p><button @click="setPasswordAction('huge')">7. password = {{password}}</button></p>
</div>
</template>
<script>
// map系を使用する場合importする
import {mapGetters} from 'vuex'
import {mapMutations} from 'vuex'
import {mapActions} from 'vuex'
export default {
computed: {
// [1.state] 直接操作(非推奨)
countDirect() {
return this.$store.state.count
},
// [2.getters] stateの値を取得
count() {
return this.$store.getters.count
},
// [3.getters] 一括でgettersを設定
...mapGetters(['name','password']),
},
methods: {
// [4.mutations] stateの値を変更
setCount() {
this.$store.commit("setCount", 1) // 第二引数はmutationに渡す値
},
// [5.mutations] 一括でmutationsを設定
...mapMutations(['setName','setPassword']) ,
// [6.actions] mutationsを起動
setCountAction() {
this.$store.dispatch('setCountAction', 2) // 第二引数はmutationに渡す値
},
// [7.actions] 一括でactionsを設定
...mapActions(['setNameAction', 'setPasswordAction'])
}
}
</script>
参考