0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vuexで初期値をセットする

0
Posted at

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");
  },
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?