localStrageへの保存
$ npm install vuex-persistedstate
plugins/localStorage.js
import createPersistedState from 'vuex-persistedstate'
export default ({ store }) => {
window.onNuxtReady(() => {
createPersistedState({})(store)
})
}
store/index.js
export const state = () => ({
isIe: false
})
export const actions = {
nuxtServerInit({ commit }, context) {
commit('setIeBrowserFlg’)
// store/auth側のstoreを呼び出す
commit('auth/setKey', stored_key)
}
}
store/auth.js
export const state = () => ({
key: ''
})
export const mutations = {
setKey(state, key) {
state.key = key
}
}
componentsで呼び出す
<p>{{ $store.state.auth.key }}</p>
this.$store.auth.key
// データを保存するにはmutationsを介さないといけない
this.$store.commit('auth/setKey', response.key)
storeのデータを消す
// 一応mutationsの中でやった。
export const mutations = {
removeKey(state) {
delete state.key
}
}
ブラウザをリロードするとlocalStrageのデータが入っていない..
どうやら、Nuxtはclientのリロードしたときの初期化の処理を別途定義しないといけないらしい。
“nuxt-client-init-module” を使った。
これで “nuxtClientInit” という関数でクライアントが初期がしたときの動作を定義できる
$ npm install nuxt-client-init-module --save
nuxt.config.js
modules: [
'nuxt-client-init-module'
],
ルートストアで クライアント起動時にlocalStorageからセットできるようにする
store/index.js
// client初期化時の動作
export const actions = {
nuxtClientInit({ commit }, context) {
let data = JSON.parse(localStorage.getItem("auth-key")) || []
commit('auth/setKey', data.auth.key)
}
}
[参考]