javascript - 加载时切换 Vue3 PrimeVue 主题/CSS 文件并单击

标签 javascript vue.js import vuejs3 primevue

包含主题的推荐方法是导入应用程序根目录的 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>

我无法在已安装和样式标签中导入任何内容,我也无法在媒体中导入任何内容,两者都不是正确的使用方式。

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

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

@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");
      })();
    },
  },

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

请指教。

最佳答案

一种解决方案是像在 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

关于javascript - 加载时切换 Vue3 PrimeVue 主题/CSS 文件并单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67309287/

相关文章:

c++ - 从 PE 导入表中获取 DLL 的完整路径

javascript - extjs组合下拉列表不适应新数据

javascript - 如何在 JavaScript 中将方法数据公开到类范围之外

javascript - 为什么我的响应式导航无法切换类别?

vue.js - 我无法在 Ubuntu 中运行 vue cli - 错误 : Unable to access jarfile/snap/vue/1/jar/vue-1. 0-SNAPSHOT.jar

vue.js - 防止vue在元素之间渲染换行符

javascript - window.location 和 location.href 的区别

javascript - 当购物车中已存在 id 时,Vue.js 购物车数量增加

php - php 文件如何找到其他 php 文件中的 namespace ?

ios - Xcode 6 中的 Parse 和 Facebook SDK 导入冲突 ("ParseFacebookUtils"无法识别)