Javascript 有什么方法可以“监视”Vuejs 中的本地存储?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42974170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to 'watch' for localstorage in Vuejs?
提问by artem0071
I'm attempting to watch for localstorage:
我正在尝试监视本地存储:
Template:
模板:
<p>token - {{token}}</p>
Script:
脚本:
computed: {
token() {
return localStorage.getItem('token');
}
}
But it doesn't change, when tokenchanges. Only after refreshing the page.
但它不会改变,当token改变时。只有在刷新页面后。
Is there a way to solve this without using Vuex or state management?
有没有办法在不使用 Vuex 或状态管理的情况下解决这个问题?
回答by Cobaltway
Sure thing! The best practice in my opinion is to use the getter/ settersyntax to wrap the localstorage in.
肯定的事!我认为最好的做法是使用getter/ setter语法来包装本地存储。
Here is a working example:
这是一个工作示例:
HTML:
HTML:
<div id="app">
{{token}}
<button @click="token++"> + </button>
</div>
JS:
JS:
new Vue({
el: '#app',
data: function() {
return {
get token() {
return localStorage.getItem('token') || 0;
},
set token(value) {
localStorage.setItem('token', value);
}
};
}
});
And a JSFiddle.
还有一个JSFiddle。
回答by arve0
If you want to avoid boilerplate (getter/setter-syntax), use vue-persistent-stateto get reactive persistent state.
如果您想避免样板文件(getter/setter 语法),请使用vue-persistent-state来获取反应性持久状态。
For example:
例如:
import persistentState from 'vue-persistent-state';
const initialState = {
token: '' // will get value from localStorage if found there
};
Vue.use(persistentState, initialState);
new Vue({
template: '<p>token - {{token}}</p>'
})
Now tokenis available as data in all components and Vue instances. Any changes to this.tokenwill be stored in localStorage, and you can use this.tokenas you would in a vanilla Vue app.
现在token可作为所有组件和 Vue 实例中的数据使用。任何更改this.token都将存储在 localStorage 中,您可以this.token像在 vanilla Vue 应用程序中一样使用。
The plugin is basically watcher and localStorage.set. You can read the code here. It
该插件基本上是观察者和localStorage.set. 您可以在此处阅读代码。它
- adds a mixinto make
initialStateavailable in all Vue instances, and - watches for changes and stores them.
- 添加一个mixin以
initialState在所有 Vue 实例中可用,并且 - 监视更改并存储它们。
Disclaimer: I'm the author of vue-persistent-state.
免责声明:我是vue-persistent-state 的作者。
回答by Lucas Morgan
The VueJs site has a page about this. https://vuejs.org/v2/cookbook/client-side-storage.html
VueJs 站点有一个关于此的页面。 https://vuejs.org/v2/cookbook/client-side-storage.html
They provide an example. Given this html template
他们提供了一个例子。鉴于此 html 模板
<template>
<div id="app">
My name is <input v-model="name">
</div>
<template>
They provide this use of the lifecycle mountedmethod and a watcher.
它们提供了生命周期mounted方法和观察者的这种用法。
const app = new Vue({
el: '#app',
data: {
name: ''
},
mounted() {
if (localStorage.name) {
this.name = localStorage.name;
}
},
watch: {
name(newName) {
localStorage.name = newName;
}
}
});
The mountedmethod assures you the nameis set from local storage if it already exists, and the watcher allows your component to react whenever the name in local storage is modified. This works fine for when data in local storage is added or changed, but Vue will not react if someone wipes their local storage manually.
如果本地存储已经存在,该mounted方法确保您name从本地存储中设置它,并且只要本地存储中的名称被修改,观察者就会允许您的组件做出反应。这适用于添加或更改本地存储中的数据时,但如果有人手动擦除其本地存储,Vue 将不会做出反应。
回答by Salam
localStorageis not reactive but I needed to "watch" it because my app uses localstorage and didn't want to re-write everything so here's what I did using CustomEvent.
localStorage不是反应性的,但我需要“观看”它,因为我的应用程序使用本地存储并且不想重写所有内容,所以这就是我使用CustomEvent.
I would dispatch a CustomEventwhenever you add something to storage
CustomEvent每当您向存储中添加内容时,我都会发送
localStorage.setItem('foo-key', 'data to store')
window.dispatchEvent(new CustomEvent('foo-key-localstorage-changed', {
detail: {
storage: localStorage.getItem('foo-key')
}
}));
Then where ever you need to watch it do:
然后在您需要观看的地方执行以下操作:
mounted() {
window.addEventListener('foo-key-localstorage-changed', (event) => {
this.data = event.detail.storage;
});
},
data() {
return {
data: null,
}
}
回答by Yash Ojha
you can do it in two ways,
你可以通过两种方式做到这一点
by using vue-lsand then adding the listener on storage keys, with
Vue.ls.on('token', callback)or
this.$ls.on('token', callback)by using storage event listener of DOM:
document.addEventListener('storage', storageListenerMethod);
通过使用vue-ls然后在存储键上添加侦听器,使用
Vue.ls.on('token', callback)或者
this.$ls.on('token', callback)通过使用 DOM 的存储事件侦听器:
document.addEventListener('storage', storageListenerMethod);

