Vuejs SPA动态主题

Mon*_*ana 5 html javascript css webpack vue.js

我已经构建了一个 Vuejs 单页面应用程序,我想添加用户可切换的动态主题。用户在某处或某处有一个按钮,他们可以单击“浅色”或“深色”主题选项,整个应用程序会立即更新。我还想让所有“主题”scss 文件都位于本地。

这里的答案是迄今为止我找到的最接近的答案,但主题不是本地的。

const themes = {
  flatly: "https://bootswatch.com/4/flatly/bootstrap.min.css",
  materia: "https://bootswatch.com/4/materia/bootstrap.min.css",
  solar: "https://bootswatch.com/4/solar/bootstrap.min.css"
};
Run Code Online (Sandbox Code Playgroud)

如果我能弄清楚如何让这个答案与本地主题文件一起使用,那就太好了,但是用本地路径切换链接路径是行不通的。

const themes = {
  dark: "dark-theme.scss",
  light: "light-theme.scss"
};
Run Code Online (Sandbox Code Playgroud)

我怀疑这不起作用,因为 Webpack 或其他一些不包含 scss 文件的编译问题。

我发现如果我将以下内容添加到我的 index.html 中,我可以让我的主题文件出现在客户端源中, <link rel="stylesheet" type="text/css" href="<%= BASE_URL %>dark-theme.scss"> 但是我不知道如何在我的应用程序中引用它。也许像这样的链接http://localhost:8080/dark-theme.scss?但我认为这在生产中不起作用(而且它在本地也不起作用)。

我也看过:

  • 与上面链接的答案类似,并且遇到类似的问题
  • 例如, this仅具有 scss 变量,无法向类添加属性
  • 我认为这不是一个非常干净的解决方案,因为它需要所有组件了解主题等

我也尝试过import "@/path/to/theme.scss";在我的main.ts文件中做一些确实有效的事情,但我不知道如何利用它来使主题可切换。它只是在我的头上添加了一个如下所示的元素,该元素没有 id 或类,因此我无法有效地查询它以将其切换出来。使用require也可以做类似的事情。

<style type="text/css" >
  ...
</style>
Run Code Online (Sandbox Code Playgroud)

Ren*_*aud 2

主要.ts:

import "@/path/to/dark-theme.scss"
import "@/path/to/light-theme.scss"
Run Code Online (Sandbox Code Playgroud)

黑暗主题.scss:

body.dark {
  /* rest of the theme */
}
Run Code Online (Sandbox Code Playgroud)

浅色主题.scss:

body.ligh {
  /* rest of the theme */
}
Run Code Online (Sandbox Code Playgroud)

index.html(或根据本地存储或操作系统模式从 main.ts 注入):

<body class="light">
Run Code Online (Sandbox Code Playgroud)

你的开关在哪里:

methods: {
  toggleTheme() {
    document.body.classList.toggle('dark')
    document.body.classList.toggle('light')
  }
}
Run Code Online (Sandbox Code Playgroud)