# Vant

一款移动端组件库 官方传送门 (opens new window)

# 定制主题(Vant2)

注意: 这个在vant3中已废弃
官方传送门 (opens new window)

# 步骤1 引入.less样式源文件

// main.js
// 这个是之前引入组件的使用方法
import Vant from 'vant'
import 'vant/lib/index.css'
// 现在 需要将引入的index.css改成index.less (为了能够覆盖默认的less变量)
import 'vant/lib/index.less'
1
2
3
4
5
6

# 步骤2 修改样式变量

这是官方提供的代码,直接copy的

// 暂不推荐这么写
// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      less: {
        // 若 less-loader 版本小于 6.0,请移除 lessOptions 这一级,直接配置选项。
        // 所以项目 是需要安装less的
        lessOptions: {
          modifyVars: {
            // 直接覆盖变量
            'text-color': '#111',
            'border-color': '#eee',
            // 或者可以通过 less 文件覆盖(文件路径为绝对路径)
            // hack: `true; @import "your-less-file-path.less";`,
          },
        },
      },
    },
  },
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

注意

直接覆盖变量的方法:一般开发的时候 不会这么写
因为每次修改完项目的配置文件,项目需要重启,非常麻烦

所以需要用文件覆盖的方式

  • 所以:创建一个.less文件 里面放覆盖样式的代码.

  • 这里提到需要 文件是用绝对路径(盘符开始)

    webpack在进行打包的时候,底层用到了node.js 所以在vue.config.js配置文件中,可以导入并使用node.js中的核心模块

# 最终写法

// vue.config.js
const path = require('path')
const themePath = path.join(__dirname,'./src/theme.less')

module.exports = {
  css: {
    loaderOptions: {
      less: {
        // 若 less-loader 版本小于 6.0,请移除 lessOptions 这一级,直接配置选项。
        // 所以项目 是需要安装less的
        lessOptions: {
          modifyVars: {
            // 或者可以通过 less 文件覆盖(文件路径为绝对路径)
            hack: `true; @import "${themePath}";`,
          },
        },
      },
    },
  },
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 全局配置(Vant3 中的定制主题)

# ConfigProvider 全局配置

ConfigProvider 仅影响它的子组件的样式,不影响全局 root 节点

<template>
  <div>
    vant 主题定制
    <div class="txt">测试</div>
    <van-button type="primary">主要按钮</van-button>
    <!-- ConfigProvider全局配置:  -->
    <van-config-provider :theme-vars="themeVars">
      <van-button type="primary">主要按钮</van-button>
    </van-config-provider>
  </div>
</template>

<script>
export default {
  name: 'WorkspaceJsonDemo1',
  data() {
    return {
      // themeVars 来修改
      themeVars: {
        buttonPrimaryBackgroundColor: 'red',
      }
    }
  }
}
</script>

<style lang="less" scoped>
.txt {
  /* 可以使用 :root下的全局样式 */
  color: var(--van-button-primary-background-color);
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

结果

# 直接css覆盖

  • 注意: 这个是全局覆盖的 影响项目的全部的组件样式

在实际开发中,影响全局的样式,不适合写在单独的vue文件中

<style>
:root {
  --van-button-primary-background-color: rgb(126, 191, 228);
}
</style>
1
2
3
4
5
  • 项目全局的定制vant主题:(需要以下这么写)
  1. 在单独的css文件中 写好主题样式
  2. app.vue 中就引入全局的样式
/* theme.css */
:root {
  --van-button-primary-background-color: rgb(81, 202, 87);
}
1
2
3
4
// app.vue 中就引入全局的样式
<style src="./styles/theme.css"></style>

// 或者
<style>
@import './styles/theme.css';
</style>
1
2
3
4
5
6
7
  • 问题 自己在项目中测试的时候,需要加一个!important 样式才起效果
Last Updated: 9/23/2022, 4:13:27 PM