定制主题

介绍

Vant 提供了一套默认主题,CSS 命名采用 BEM 的风格,方便使用者覆盖样式。如果你想完全替换主题色或者其他样式,可以使用下面提供的方法

示例工程

我们提供了一个基于 Vue Cli 3 的示例工程,仓库地址为 Vant Demo,其中包含了定制主题的基本配置,可以作为参考。

样式变量

Vant 使用了 Less 对样式进行预处理,并内置了一些样式变量,通过替换样式变量即可定制你自己需要的主题。

下面是一些基本的样式变量,所有可用的颜色变量请参考 配置文件

  1. // color variables
  2. @black: #000;
  3. @white: #fff;
  4. @red: #f44;
  5. @blue: #1989fa;
  6. @orange: #ff976a;
  7. @orange-dark: #ed6a0c;
  8. @orange-light: #fffbe8;
  9. @green: #07c160;
  10. @gray: #c9c9c9;
  11. @gray-light: #e5e5e5;
  12. @gray-darker: #7d7e80;
  13. @gray-dark: #969799;
  14. // default colors
  15. @text-color: #323233;
  16. @border-color: #ebedf0;
  17. @active-color: #f2f3f5;
  18. @background-color: #f8f8f8;
  19. @background-color-light: #fafafa;

定制方法

定制主题分为两步:引入样式源文件和修改样式变量

步骤一. 引入样式源文件

Vant 支持通过 babel 插件按需引入和手动引入两种方式,推荐使用按需引入的方式。

  1. // 在 babel.config.js 中配置按需引入样式源文件
  2. // 注意:babel6 不支持按需引入样式,请手动引入
  3. module.exports = {
  4. plugins: [
  5. [
  6. 'import',
  7. {
  8. libraryName: 'vant',
  9. libraryDirectory: 'es',
  10. // 指定样式路径
  11. style: name => `${name}/style/less`
  12. },
  13. 'vant'
  14. ]
  15. ]
  16. };

下面是手动引入的方法:

  1. // 手动引入组件的样式源文件
  2. import Button from 'vant/lib/button';
  3. import 'vant/lib/button/style/less';

步骤二. 修改样式变量

使用 less 提供的 modifyVars 即可对变量进行修改,下面是参考的 webpack 配置。

  1. // webpack.config.js
  2. module.exports = {
  3. rules: [
  4. {
  5. test: /\.less$/,
  6. use: [
  7. // ...other loaders
  8. {
  9. loader: 'less-loader',
  10. options: {
  11. modifyVars: {
  12. red: '#03a9f4',
  13. blue: '#3eaf7c',
  14. orange: '#f08d49',
  15. 'text-color': '#111'
  16. }
  17. }
  18. }
  19. ]
  20. }
  21. ]
  22. };

定制主题  - 图1