Nuxt引用cookie-universal-nuxt在服务端请求cookie方式
Nuxt引用cookie-universal-nuxt在服务端请求cookie
npm install cookie-universal-nuxt -s
在nuxt.config.js添加
modules: [ 'cookie-universal-nuxt' ],
设置cookie
this.$cookies.set('token', 123456)获取cookie
this.$cookies.get("token")清除cookie
this.$cookies.remove('token')在asyncData获取
async asyncData({ app }) {
console.log(app.$cookies.get("token"));
},nuxt cookie-universal-nuxt 搭配 vuex-persistedstate 做数据持久化
因为服务端不存在 Local Storage 和 Session Storage
所以 便使用了 cookie-universal-nuxt 这个插件
在做Nuxt项目的时候 发现Vuex 在刷新页面后 储存的数据丢失
用 vuex-persistedstate 来持久化数据
cookie-universal-nuxt 安装
cookie-universal-nuxt 的安装
npm install cookie-universal-nuxt -s
打开 nuxt.config.js 文件
在 modules 下添加
modules: [ ? ? // https://go.nuxtjs.dev/axios ? ? 'cookie-universal-nuxt' ? ],
更多使用方法请点击 传送门
vuex-persistedstate安装
安装命令
npm install vuex-persistedstate --save
配合 cookie-universal-nuxt 使用
在 plugins文件夹下新建 文件 persistedState.js
import createPersistedState from 'vuex-persistedstate'
export default ({ app, store }) => {
createPersistedState({
storage: {
getItem: (key) => app.$cookies.get(key),
setItem: (key, value) =>
app.$cookies.set(key, value, {
path: '/',
maxAge: 60 * 60 * 24 * 1 // cookie存储时间 可修改
}),
removeItem: (key) => app.$cookies.remove(key)
}
})(store)
}打开 nuxt.config.js 文件
在 piugins 模块下进行导入
plugins: [
'@/plugins/persistedState',
],到此 使用 cookie就可以进行持久化储存
使用方式
this.$cookies.set('token', 'XXXXXXXXXXXXXXXXXXXX')就正常的使用 cookie-universal-nuxt 的方式即可
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue3使用vuex实现页面实时更新数据实例教程(setup)
在前端开发中往往会遇到页面需要实时刷新数据的情况,给用户最新的数据展示,这篇文章主要给大家介绍了关于vue3使用vuex实现页面实时更新数据(setup)的相关资料,需要的朋友可以参考下2022-09-09
vue3 ElementUI 日期禁选当日前当日后三天后的实现代码
这篇文章主要介绍了vue3 ElementUI 日期禁选当日前当日后三天后的实现代码,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧2024-05-05


最新评论