【问题标题】:Vuex cookie storageVuex cookie 存储
【发布时间】:2018-07-14 03:08:34
【问题描述】:

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    如果您想获取该数据,可以使用以下代码: localStorage.getItem('data')

    还有关于localStorage,看看这个Window.localStorage - Web APIs | MDN

    【讨论】:

    • 那太好了,如何在私人模式下处理 safari?
    • 为什么是本地存储?如果他想使用 cookie,他可能想存储会话数据......
    • 也不应该使用本地存储来存储敏感数据
    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2011-05-17
    • 1970-01-01
    • 2022-01-09
    • 2019-07-28
    • 2019-05-26
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多