VueJS - 如何查看 localStorage 中的值? [英] VueJS - how to watch a value in localStorage?

查看:90
本文介绍了VueJS - 如何查看 localStorage 中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 nav 组件,它只需要在 localStorage 中存储了令牌时才需要显示.当该令牌从 localStorage 中删除时,nav 组件需要注意变化并隐藏自身.

I have a nav component that needs to only be shown when there is a token stored in localStorage. When that token is deleted from localStorage the nav component needs to notice that change and hide itself.

解决这个问题的最佳方法是什么?

What's the best way to approach this?

推荐答案

Local Storage 不是响应式的,因此您需要将令牌存储在某个位置.我假设您的令牌正在由应用程序设置和删除.如果是这样,最好的处理方法是使用像 Vuex 这样的状态(参见 Vue 状态管理).

Local Storage is not reactive, so you need to store your token in some place that is. I assume your token is being set and deleted by the application. If so, the best way to handle this is to use state like Vuex (see Vue State Management).

选项 1

如果您使用本地存储来在多个浏览器会话之间保留令牌,最好的选择是在 Vuex 中设置令牌,然后使用 Vuex 持久化状态 将 Vuex 同步到本地或会话存储.当您需要重新建立状态时,插件会再次检索它.

If you are using local storage in order to retain the token between multiple browser sessions, the best option is to just set the token in Vuex then use Vuex persisted state to sync Vuex to local or session storage. The plugin will retrieve it again when you need to re-establish state.

选项 2

如果您需要直接在本地存储中设置它,您应该在更改状态时包含在您的更改中以设置/取消设置 localStorage.这将使您的 localStorage 和 State 保持同步.

If you need it set in the local storage directly, you should include in your mutations to set/unset the localStorage when you are changing the state. This will keep your localStorage and State in sync.

例如使用 Vuex,如果您在响应中收到令牌,则可以调用 Mutation 将其设置为 Vuex 状态以及将其设置为 localStorage:

For example using Vuex, if you are receiving a token in a response you can then call a Mutation to set it in Vuex state as well as set it to localStorage:

SET_TOKEN(state, payload){
    state.token = payload.token 
    localStorage.setItem('token', payload.token)
}

然后您可以轻松查看 Vuex 状态.根据您的 Vuex 的设置方式,它可能类似于:this.$store.state.token

You can then easily watch the Vuex state. Depending on how your Vuex is set up, it may be something like: this.$store.state.token

这篇关于VueJS - 如何查看 localStorage 中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆