大規模な開発に向いている状態管理パターンとライブラリ。
下記コマンドを実行
npm install vuex
src直下にstore.jsを作成。importで読み込む。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
}
});
state:はvue全体で使用できるグローバル変数。
main.jsでstoreを読み込み、すべてのVueコンポーネントでstoreが使用できるように設定する。
import store from './store.js'
new Vue({
store
}).$mount('#app')
各コンポーネントでstoreで設定したグローバル変数を利用する方法
仮置きで、storeのstateにnameという関数を設ける。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
name:'Mory'
}
});
Home.vueコンポーネント上でnameを表示させる。
<template>
<div>
<p>{{name}}</p>
</div>
</template>
<script>
export default {
computed:{
name(){
return this.$store.state.name;
}
}
};
</script>
呼び出しは、computedを使用。
main.jsで読み込んだため$storeで全てのコンポーネントにアクセスが可能。
