【问题标题】:Switch Vue3 theme / CSS file on load and click在加载时切换 Vue3 主题/CSS 文件并单击
【发布时间】:2021-07-22 08:16:12
【问题描述】:

包含主题的推荐方式是在应用根目录下的main.js 文件中导入:

import 'primevue/resources/themes/arya-orange/theme.css';

但我正在寻找一种基于用户系统主题和用户选择来切换 CSS 文件的方法,所以我将它移到了我的主 App.vue

export default {
  name: "App",
  components: {
    HelloWorld,
    toDo,
  },
  mounted() {

    //window.matchMedia('(prefers-color-scheme: dark)').matches ? do dark : do light
  },
};

<style>
@media (prefers-color-scheme: dark) {
  @import url("primevue/resources/themes/bootstrap4-dark-blue/theme.css");
}
@media (prefers-color-scheme: light) {
  @import url("primevue/resources/themes/bootstrap4-light-blue/theme.css");
}
</style>

我无法在mounted 和styles 标签中导入任何东西,我也无法在media 中导入任何东西,这两种方法都不是正确的使用方式。

我在网上找不到任何其他方法或指导来解决这个问题。所有解决方案都基于范围组件、使用类等。

我可以将所有规则包装在一个主题中

@media (prefers-color-scheme: dark) {

还有一个用于灯光。但话又说回来,我怎么能打开用户选择呢?

编辑:

我找到了一种让它在负载下工作的方法:

(async () => {
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    await import('primevue/resources/themes/bootstrap4-dark-blue/theme.css');
  }else {
    await import('primevue/resources/themes/bootstrap4-light-blue/theme.css');
  }
})();

点击后会覆盖第一次导入:

  methods: {
    theme() {
      (async () => {
          await import("primevue/resources/themes/bootstrap4-light-blue/theme.css");
      })();
    },
  },

但是当我尝试使用单击将其切换回来时,它什么也不做,我的猜测是因为如果系统是黑暗的,它会在加载时加载深色主题作为第一次导入,然后点击它会加载浅色主题,但在那之后它不会在点击时切换回黑暗,我的猜测是因为黑暗在加载时已经准备好加载并且它不会在切换时生效。

请指教。

【问题讨论】:

    标签: javascript vue.js import vuejs3 primevue


    【解决方案1】:

    一种解决方案是在 PrimeVue 站点中实施。综上所述,css主题是通过index.html文件中的链接导入的:

    <!DOCTYPE html>
    <html lang="en">
        <head>
    ...
    <link id="theme-link" rel="stylesheet" href="<%= BASE_URL %>themes/saga-blue/theme.css">
        </head>
        <body>
    ...
        </body>
    </html>
    

    有关示例,请参阅 this link

    然后要切换主题,你可以在这样的函数中实现它:

    changeTheme(event) {
        let themeElement = document.getElementById('theme-link');
        themeElement.setAttribute('href', themeElement.getAttribute('href').replace(this.theme, event.theme));
        this.theme = event.theme;
        this.activeMenuIndex = null;
        EventBus.emit('change-theme', event);
        this.$appState.darkTheme = event.dark;
        if (event.theme.startsWith('md')) {
            this.$primevue.config.ripple = true;
        }
        localStorage.setItem('theme', this.theme);
    }
    

    这就是它在 PrimeVue 文档中的实现方式。见here

    【讨论】:

    • 旧时尚哈? :) 我会接受它,它完成了工作我看到了 PrimeVue 的一些演示 git,但不是主站点,非常感谢您的信息!
    猜你喜欢
    • 2022-10-17
    • 2012-03-07
    • 2016-07-26
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2014-10-23
    • 1970-01-01
    相关资源
    最近更新 更多