鈍足ランナーのIT日記

走るのが好きな5流のITエンジニアのブログ。

趣味の範囲は広いけど、どれも中途半端なクソブロガー楽しめるWebアプリを作ってあっと言わせたい。サーバーサイドPerl(Mojolicious)、クライアントサイドVue.js。Arduinoにも触手を伸ばす予定。

vuexを使ってlocalstorageへ保存する

要件は

コンポーネントA,Bがあり、コンポーネントBが設定画面とします。
コンポーネントBの保存ボタンを押すと、storeに格納されて
コンポーネントAでも保存した値が参照できるようにしたい。
保存ボタンではローカルストレージに格納する

こうするといいかも

main.jsの中のbeforeCreateの中で、storeのmutationを呼び出して、localStorageから読み出す。
コンポーネントBのmountedメソッドの中で、storeのstateを参照して自身のプロパティとして保存する
コンポーネントAのcomputedメソッドの中でstoreのstateを参照する

https://www.mikestreety.co.uk/blog/vue-js-using-localstorage-with-the-vuex-store


さて、やってみましょう。

vuexのインストール

npm install vuex --save

Storeの作成

storeディレクトリを掘りstore.jsを作成する

store.js

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

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    repeatInterval: 15
  },
  mutations: {
    setRepeatInterval (state, repeatInterval) {
      state.repeatInterval = repeatInterval
      localStorage.setItem('store', JSON.stringify(state))
    },
    initializeStore (state) {
      if (localStorage.getItem('store')) {
        this.replaceState(Object.assign(state, JSON.parse(localStorage.getItem('store'))))
      } 
    }
  }
})

main.jsの編集

起動時に読み込むエントリーポイントはAppコンポーネントから行うと
見通しも良さそう?!
main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.css'
import { store } from './store/store.js'

Vue.use(Vuetify)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  store: store,
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  beforeCreate () {
    this.$store.commit('initializeStore')
  }
})

設定用コンポーネントの定義(抜粋)

<template>
    <v-text-field ref="input" v-model="repeatInterval"><{{repeatInterval}}</v-text-field>
</template>

<script>
export default {
  name: 'ogura',
  created () {
  },
  data () {
    return {
      repeatInterval: null
    }
  },
  methods: {
    update () {
      this.$store.commit('setRepeatInterval', this.$refs.input.value)
    }
  },
  mounted () {
    this.repeatInterval = this.$store.state.repeatInterval
  }
}
</script>