历史搜索

Vue前端实现 ”一键换肤“ 方法

游客2024-09-22 07:53:01
目录文章目录
  1.  一、技术核心
  2. 二、实现方法
  3. 结语

我们网站在迭代升级时,经常会被产品要求更换网站配色这样的需求,或者提供入口,让用户自己选择页面的配色主题。那么我们该怎么去实现这种需求呢?下面一起和博主看看 Vue 实现前端 ”一键换肤“ 方法。

 一、技术核心

通过切换 css 选择器的方式实现主题样式的切换.

  • 组件中保留不变的样式,将需要变化的样式进行抽离;
  • 提供多种样式,给不同的主题定义一个对应的 CSS 选择器;
  • 根据不同主题通过切换 CSS 选择器设置不同的样式。

二、实现方法

提取公共 CSS 样式, 通过变量的形式切换主题

1、新建一个存放公共 css 变量的 variable.js 文件,将需要定义的 css 变量存放到该 js 文件,通过 css-vars-ponyfill 插件换肤。

// variable.js
// 字体变量
const baseSize = {
  "--font-size-first-level-title": "18px",
  "--font-size-second-level-title": "16px",
};

// 浅色
export const lightTheme = {
  "--themeColor": "#01cc8c",
  "--left-bg": "rgb(182, 23, 23)",
  "--right-bg": "rgb(63, 9, 9)",
  "--top-bg": "rgb(6, 36, 65)",
  "--bottom-bg": "rgb(55, 214, 10)",
  ...baseSize,
};

// 深色
export const darkTheme = {
  "--themeColor": "#56518C",
  "--left-bg": "#0094ff",
  "--right-bg": "blue",
  "--top-bg": "red",
  "--bottom-bg": "pink",
  ...baseSize,
};

2、在页面中使用 css 变量。

<style lang="sass">
  .left {
      background-color: var(--left-bg);
    	color: var(--themeColor);
      height: 500px;
      flex: 1;
    }
</style>

3、安装 css-vars-ponyfill 插件。

npm i css-vars-ponyfill

4、封装切换主题的 js

// theme.js
import { lightTheme, darkTheme } from "../src/assets/js/variable";
import cssVars from "css-vars-ponyfill";
export const initTheme = (theme = true) => {
  document.documentElement.setAttribute("data-theme", theme ? "light" : "dark");
  cssVars({
    watch: true, // 当添加,删除或修改其<link>或<style>元素的禁用或 href 属性时,ponyfill 将自行调用
    variables: theme ? lightTheme : darkTheme, // variables 自定义属性名/值对的集合
    onlyLegacy: false, // false  默认将 css 变量编译为浏览器识别的 css 样式  true 当浏览器不支持 css 变量的时候将 css 变量编译为识别的 css
  });
};

5、main.js 中调用 theme.js

import { initTheme } from './theme'
let theme = 条件 ? false : true
initTheme(theme)

6、图片路径如何解决?

// main.js
// lightTheme 和 darkTheme 是文件夹名字
Vue.prototype.SKIN_IMAGE_PATH = 条件 ? 'lightTheme' : 'darkTheme'
// .vue 文件
export default {
  data () {
    return {
      tip: require(`@assets/img/theme/${this.SKIN_IMAGE_PATH}/tip.png`),
    }
  }
}

结语

以上就是关于前端“一件换肤”的技术方案,希望对大家有用,感谢阅读。