Javascript Vuex cookie存储

Javascript Vuex cookie存储,javascript,vue.js,nuxt.js,Javascript,Vue.js,Nuxt.js,我使用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 = () => ({

我使用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>

超级机密页面,你好{{user}
如果您试图访问此未连接的URL,您将看到错误页面,告知您未连接

返回主页 导出默认值{ 计算:{ 用户(){ 返回store.state.count } }, 中间件:“auth” }

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

您可以使用
localStorage
来持久化数据,这里是示例

actions: {
  setData ({commit}, payload) {
    localStorage.setItem('data', payload)
    commit('setData')
  }
}
如果你想得到这些数据,你可以使用以下代码:
localStorage.getItem('data')


此外,关于
localStorage
,请查看此正确的处理方法是在您的存储中使用
nuxtServerInit
操作。这样,您将确保在呈现之前在服务器端调用它

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

太好了,你是如何在私有模式下处理safari的?为什么是本地存储?如果他想使用cookie,他可能想存储会话数据……本地存储也不应用于存储敏感数据