首页 > 解决方案 > '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 秒获取一次值,但我认为这会减慢我的应用程序的速度。

是否有其他替代方法可以在不进行轮询的情况下侦听本地存储项目更改?

标签: vue.jslocal-storagecomputed-properties

解决方案


这正是观察者模式的用途。您创建一个事件“OnAppThemeChange”。您可以使用所有组件订阅该事件。然后,每当您的应用主题更改时,您就会调用您的事件,所有组件都会刷新它们的应用主题。

这消除了每 2 秒刷新一次主题的需要。它只会在您实际更改主题时刷新。

有用的链接:

https://developer.mozilla.org/de/docs/Web/Guide/Events/Creating_and_triggering_events https://refactoring.guru/design-patterns/observer


推荐阅读