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 做數(shù)據(jù)持久化
因為服務端不存在 Local Storage 和 Session Storage
所以 便使用了 cookie-universal-nuxt 這個插件
在做Nuxt項目的時候 發(fā)現(xiàn)Vuex 在刷新頁面后 儲存的數(shù)據(jù)丟失
用 vuex-persistedstate 來持久化數(shù)據(jù)
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 的方式即可
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
el-form resetFields無效和validate無效的可能原因及解決方法
本文主要介紹了el-form resetFields無效和validate無效的可能原因及解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08

