Vuex cookie存储

问题描述 投票:3回答:2

我用vuex和nuxt开发了一个Vue js应用程序,有这个存储空间:

import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

Vue.use(Vuex)

export const state = () => ({
  authUser: null,
  sidebar: false
})

export const mutations = {
  toggleSidebar (state) {
    state.sidebar = !state.sidebar
  },
  SET_USER: function (state, user) {
    state.authUser = user
  }
}

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  strict: debug,
  plugins: [createPersistedState({
    storage: {
      getItem: key => Cookies.get(key),
      setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
      removeItem: key => Cookies.remove(key)
    }
  })]
})

// Polyfill for window.fetch()
require('whatwg-fetch')

export const actions = {
  // nuxtServerInit is called by Nuxt.js before server-rendering every page
  async login ({ commit }, { username, password }) {
    try {
      // const { data } = await axios.post('/api/login', { username, password })
      var data = username
      console.log(data)
      commit('SET_USER', data)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('Bad credentials')
      }
      throw error
    }
  },

  async logout ({ commit }) {
    await axios.post('/api/logout')
    commit('SET_USER', null)
  }
}

以下模板:

<template>
  <div>
    <h1>Super secret page, hello {{user}}</h1>
    <p>If you try to access this URL not connected, you will see the error page telling your that you are not connected.</p>
    <nuxt-link to="/">Back to the home page</nuxt-link>
  </div>
</template>

<script>
export default {
  computed: {
    user () {
      return store.state.count
    }
  },
  middleware: 'auth'
}
</script>

问题是,如果我在浏览器中重新打开选项卡或点击ctrl + f5(因此实际上没有创建cookie),我将丢失所有存储数据。此外,我无法访问我的模板中的用户名,是否还有其他“正确”的方式来访问存储?

javascript vue.js nuxt.js
2个回答
-1
投票

处理它的正确方法是在商店中使用nuxtServerInit操作。这样你就可以确保在渲染之前在服务器端调用它。

export const actions = {
 nuxtServerInit ({dispatch}, context) {
  // your logic
 }
}

-3
投票

您可以使用localStorage来保存数据,这里是示例

actions: {
  setData ({commit}, payload) {
    localStorage.setItem('data', payload)
    commit('setData')
  }
}

如果你想获得这些数据,你可以使用这个代码:localStorage.getItem('data')

此外关于localStorage,看看这个Window.localStorage - Web APIs | MDN

© www.soinside.com 2019 - 2024. All rights reserved.