简体   繁体   English

如何在本地存储 Nuxt.js 中保存用户连接?

[英]How save user connection in Local storage Nuxt.js?

I am making an application in nuxt.js, I use a store to store data including the user who connects and I want to keep the user's connection elements in the localStorage.我正在 nuxt.js 中创建一个应用程序,我使用商店来存储数据,包括连接的用户,我想将用户的连接元素保存在 localStorage 中。 So to do this I used a plugin which is vuex-persist of which here is the code.为此,我使用了一个 vuex-persist 插件,代码如下。

Here is my store/login.js:这是我的商店/login.js:

 export const state = () => ({ user: '' }) export const mutations = { setUser(state, newUser) { state.user = newUser; } } export const getters = { getUser(state) { return state.user } }

Here is my plugin/vuex-persist.js:这是我的插件/vuex-persist.js:

 import VuexPersistence from 'vuex-persist'; export default ({ store }) => { window.onNuxtReady(() => { new VuexPersistence({ key: "vuex", storage: window.localStorage, reducer: state => ({ login: state.login }), }).plugin(store); }); };

So this saves the user in localStorage, for example:所以这会将用户保存在 localStorage 中,例如:

在此处输入图像描述

But when I refresh the page or when I open a new page in a new tab I have to reconnect all the time.但是当我刷新页面或在新选项卡中打开新页面时,我必须一直重新连接。

I don't understand why because when I don't put a reducer function in my plugin I don't need to constantly reconnect but the problem is that it doesn't just save the user in localStorage.我不明白为什么,因为当我不在我的插件中放置 reducer function 时,我不需要不断地重新连接,但问题是它不只是将用户保存在 localStorage 中。

Thanks for your help谢谢你的帮助

I do not know the issue with your plugin, maybe it isn't registered correctly within nuxt.config.js?我不知道你的插件有什么问题,也许它没有在 nuxt.config.js 中正确注册?

// Inside - nuxt.config.js
export default {
   plugins: [{ src: '~/plugins/vuex-persist.js', mode: 'client' }],
}

or the issue could be the use of the plugin in combination with:或者问题可能是将插件与以下内容结合使用:

  window.onNuxtReady(() => {

since i personally never needed the onNuxtReady with the loading of any external plugins/libraries and within the documentation of said plugin it isn't mentioned.因为我个人从不需要加载任何外部插件/库的 onNuxtReady 并且在所述插件的文档中没有提到它。

Nevertheless, you could look into using the library vuex-persistedstate which basically does the exact same thing and i never had any issues with it.不过,您可以考虑使用库vuex-persistedstate ,它基本上做完全相同的事情,我从来没有遇到过任何问题。

Apologies for not really answering your question but i thought maybe suggesting the other library could help you or anyone else抱歉没有真正回答你的问题,但我想也许建议其他图书馆可以帮助你或其他任何人

Vuex-persisted is not maintained you can use vuex-along https://github.com/boenfu/vuex-along pretty much the same i cannot comment thats why using answer. Vuex-persisted 没有维护你可以使用 vuex-along https://github.com/boenfu/vuex-along几乎一样我不能评论这就是为什么使用答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM