Vuexで初期値をセットする方法
Vuexで初期値をサーバーから取得してセットする方法を記述します。
環境
Vue 2.5.17
Vuex 3.6.2
参考サイト
実装例
Vuexのインスタンスに初期化用のメソッドを作成します。
例ではinit
と命名していますが名前は任意です。Ajaxでデータを取得しセットします。
const store = new Vuex.Store({
state: {
userId: "",
userName: ""
},
// ...
actions: {
init() {
// ajaxで初期値を取得し、stateにセットします。
axios.post("/api/vuexInit").then(response => {
this.state.userId = response.data.user_id;
this.state.userName = response.data.user_name;
}).catch(error => {
console.error(error);
});
},
}
});
上記で定義したメソッドをVueコンポーネントのcreated
などで呼び出すことで初期値をセットできます。
created: function () {
this.$store.dispatch("init");
},