LoginSignup
9
11

More than 5 years have passed since last update.

Vuexのstoreの、load・unload時の復元・保存

Last updated at Posted at 2017-06-12

概要

TodoMVC - Vue.jsほどリアルタイムでなく、Electronアプリ≒ウィンドウ起動・終了時に復元・保存できればいい考え。

となると、
Vue インスタンス - Vue.js
に則り、メインのルートコンポーネントの生成と破棄時イベントに設定すればいいかと思ったが、数個引っかかったので残す。

ただ、保存処理がスッキリしないので、できればvue内で完結したい。

結論

  • (軽く試した限り)destroyed,beforeDestroy時には操作できなかった。
    • イベント自体が未発火なのか、localStorage操作ができないタイミングなのか、Vuex操作が出来ないタイミングなのかは未調査
    • なので、windowなどへbeforeunload時のイベントとして登録しよう。
  • stateはオブジェクトまるごと上書きは出来ないので、各stateをそれぞれ上書きしよう

検証環境

node -v
v6.9.1
package.json
{
  "dependencies": {
    "electron": "^1.6.8",
    "vue": "^2.3.3",
    "vue-loader": "^12.1.0",
    "vue-material": "^0.7.1",
    "vue-router": "^2.5.3",
    "vuex": "^2.3.1",
    "vuex-router-sync": "^4.1.2",
    "yarn": "^0.24.5"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-stage-2": "^6.24.1",
    "css-loader": "^0.28.4",
    "electron-packager": "^8.7.0",
    "style-loader": "^0.18.1",
    "vue-template-compiler": "^2.3.3",
    "webpack": "^2.6.0"
  }

コード

state変更は含んでいない。

main.js
import Vue from 'vue';
import app from './app.vue';
import store from './store.js';

new Vue({
    store,
    render: h => h(app),
}).$mount('#app');
app.vue
<template>
<div id='app'>
</div>
</template>

<script>
import { mapActions, mapGetters} from 'vuex'

export default {
  name: 'app',
  methods: {
    ...mapActions(['set_state']),
  },
  computed :{
    ...mapGetters(['all_state']),
  },
  created() {
    const state = JSON.parse(localStorage.getItem('state'));
    if (state != null) {
      this.set_state({state})
    }
    // 終了時の動作をcreate時に定義する。
    // onbeforeunload = なら上書きに注意。
    // function式ならthisに注意。.bind(this)してやるなど。
    window.addEventListener('beforeunload', () => {
      // (getterの返し方により)stateオブジェクトまるごとなので値以外も含まれているが、そんなに大きくはない
      localStorage.setItem('state', JSON.stringify(this.all_state));
    })
  },
}
</script>
store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const state = {
    hoge: '',
    huga: 0,
};

const mutations = {
    set_state(state, payload) {
        // state = payload.stateは無理
        const s = payload.state;
        state.hoge = s.hoge;
        state.huga = s.huga;
    },
};

const actions = {
    set_state({commit}, payload) {
        // (ここに限れば)特に意味はないaction
        commit('set_state', payload);
    },
};

const getters = {
    all_state(state) {
        // 特に意味はないgetter。
        return state;
    },
};

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
});

参考

javascript - Do something before reload or close in vue.js - Stack Overflow

9
11
2

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
9
11