【发布时间】: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