vue.js - 'Watching' localStorage 的变化
问题描述
我有一个 vue 应用程序,它具有可以更改主题的功能,例如light/dark
,
最初,我在我的localStorage.setItem['app_theme', 'light']
,
我在Header.vue
组件中有我的应用程序主题更换器功能,单击主题更换器切换按钮后,它也会更改localStorage['app_theme'] = 'dark'
.
现在,在我的其他组件中,我有一些computed values/variables/properties
这样的:
...
computed() {
app_card() {
return localStorage.getItem('app_theme') === 'dark' ? 'card-dark' : 'card-light'; //these are some classes with their respective theme css
},
app_text() {
return localStorage.getItem('app_theme') === 'dark' ? 'text-dark' : 'text-light'; //these are some classes with their respective theme css
}
}
...
我曾考虑使用轮询localStorage.getItem('app_theme')
每 2 秒获取一次值,但我认为这会减慢我的应用程序的速度。
是否有其他替代方法可以在不进行轮询的情况下侦听本地存储项目更改?
解决方案
这正是观察者模式的用途。您创建一个事件“OnAppThemeChange”。您可以使用所有组件订阅该事件。然后,每当您的应用主题更改时,您就会调用您的事件,所有组件都会刷新它们的应用主题。
这消除了每 2 秒刷新一次主题的需要。它只会在您实际更改主题时刷新。
有用的链接:
https://developer.mozilla.org/de/docs/Web/Guide/Events/Creating_and_triggering_events https://refactoring.guru/design-patterns/observer
推荐阅读
- php - 合并具有相同键名的多维数组
- javascript - AJAX 使用 POST 映射将所有空数据发送到 Spring 控制器?
- ios - `dd of=/dev/rdisk4` 在越狱的 iOS 上给出 `Operation not allowed`
- batch-file - 如果我运行我的 .bat(打开 FF),我可以看到窗口。从任务计划程序,它在 FF 中打开 url,但它不可见。我怎样才能明显地打开它?
- java - Spring Cloud Gateway 不适用于 DiscoveryClientRouteDefinitionLocator
- serialization - Flatbuffer 线尺寸大于预期
- javascript - 日期字段的设置值不粘
- r - 为什么我无法安装 kohonen 包 R
- c++ - 枚举属性未被识别为
- javascript - Javascript/nodejs 使用嵌套数组动态构建 JS 对象