【问题标题】:'Watching` localStorage for a change'Watching' localStorage 的变化
【发布时间】:2021-07-03 05:22:03
【问题描述】:

我有一个 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
    }
}
...

我曾考虑使用轮询每 2 秒获取一次 localStorage.getItem('app_theme') 值,但我认为这会降低我的应用程序的速度。

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

【问题讨论】:

    标签: vue.js local-storage computed-properties


    【解决方案1】:

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

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

    有用的链接:

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

    【讨论】:

    • 我不熟悉vue.js,但是观察者模式可以用任何语言实现。
    • 我是 vanillajs 的新手,但我会试试这个。如果您提供示例代码会更好:)
    • 虽然这也有效。我认为最好还是坚持使用 Vue 的标准方法并改用 vuex
    猜你喜欢
    • 2015-09-13
    • 2018-02-15
    • 2018-08-12
    • 2018-11-18
    • 2019-11-01
    • 2015-12-27
    • 2019-09-23
    • 2013-04-18
    • 2018-01-17
    相关资源
    最近更新 更多