一、Vuexの概要
1.コンポーネント間で共有するグローバルデータを管理するための仕組み 2.統一された状態管理の利点 - 共有データの集中管理により保守性が向上 - コンポーネント間でのデータ共有が簡潔に実装可能 - 呼び出されたコンポーネントに自動的に状態の更新を反映 3.適切なデータ格納の判断基準 - 共有が必要なデータはVuexに格納 - コンポーネント固有のデータは個別に保持
二、基本的な実装手順
1.パッケージの導入
npm install vuex
2.ストアファイルの作成
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
userCount: 0
},
mutations: {
updateUserCount(state, payload) {
state.userCount = payload
}
},
actions: {
asyncFetchData({ commit }) {
setTimeout(() => {
commit('updateUserCount', Math.floor(Math.random() * 100))
}, 1000)
}
},
getters: {
formattedCount: state => `現在値: ${state.userCount}`
}
})
3.Vueインスタンスへの登録
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
三、主要コンセプトの解説
1.State
// データ定義
state: {
userCount: 0
}
コンポーネントでの利用例:
<!-- テンプレート -->
<p>{{ storeUserCount }}</p>
// スクリプト
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['userCount'])
}
}
2.Mutations
mutations: {
incrementValue(state, step) {
state.userCount += step
},
decrementValue(state, step) {
state.userCount -= step
}
}
利用方法:
methods: {
updateCounter() {
this.$store.commit('incrementValue', 5)
}
}
3.Actions
actions: {
asyncUpdate({ commit }) {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
commit('updateUserCount', data.value)
})
}
}
呼び出し例:
this.$store.dispatch('asyncUpdate')
4.Getters
getters: {
processedData(state) {
return `ユーザー数: ${state.userCount}人`
}
}
利用方法:
computed: {
...mapGetters(['processedData'])
}