Vue.js ';正在监视“localStorage”以进行更改

Vue.js ';正在监视“localStorage”以进行更改,vue.js,local-storage,computed-properties,Vue.js,Local Storage,Computed Properties,我有一个vue应用程序,它有一个可以更改主题的功能,例如,light/dark 最初,我在我的localStorage.setItem['app\u theme','light']中设置了 我在Header.vue组件中有我的应用程序主题变换器功能,单击主题变换器切换按钮后,它还将更改localStorage['app\u theme']='dark' 现在,在我的其他组件中,我有一些计算值/变量/属性,如下所示: ... computed() { app_card() {

我有一个vue应用程序,它有一个可以更改主题的功能,例如,
light/dark

最初,我在我的
localStorage.setItem['app\u theme','light']
中设置了

我在
Header.vue
组件中有我的应用程序主题变换器功能,单击主题变换器切换按钮后,它还将更改
localStorage['app\u theme']='dark'

现在,在我的其他组件中,我有一些
计算值/变量/属性
,如下所示:

...
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\u theme')
值,但我认为这会减慢我的应用程序的速度


有没有其他方法可以在不轮询的情况下侦听localstorage项更改?

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

这样就不需要每2秒刷新一次主题。只有当您实际更改主题时,它才会刷新

有用链接:


我不熟悉vue.js,但observer模式可以用任何语言实现。我对vanillajs不熟悉,但我会试试这个。如果您提供一个示例代码:)会更好,而这也很有效。我认为最好还是坚持Vue的标准方法,改用
vuex