vant/src/config-provider/README.zh-CN.md
2021-06-14 10:07:00 +08:00

122 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ConfigProvider 全局配置
### 介绍
用于配置 Vant 组件的主题样式,从 3.1.0 版本开始支持。
### 引入
通过以下方式来全局注册组件,更多注册方式请参考[组件注册](#/zh-CN/advanced-usage#zu-jian-zhu-ce)。
```js
import { createApp } from 'vue';
import { ConfigProvider } from 'vant';
const app = createApp();
app.use(ConfigProvider);
```
## 定制主题
### 介绍
Vant 组件通过丰富的 [CSS 变量](https://developer.mozilla.org/zh-CN/docs/Web/CSS/Using_CSS_custom_properties) 来组织样式,通过覆盖这些 CSS 变量,可以实现**定制主题、动态切换主题**等效果。
#### 示例
以 Button 组件为例,查看组件的样式,可以看到 `.van-button--primary` 类名上存在以下变量:
```css
.van-button--primary {
color: var(--van-button-primary-color);
background-color: var(--van-button-primary-background-color);
}
```
这些变量的默认值被定义在 `root` 节点上HTML 文档的任何节点都可以访问到这些变量:
```css
:root {
--van-white: #fff;
--van-blue: #1989fa;
--van-button-primary-color: var(--van-white);
--van-button-primary-background-color: var(--van-blue);
}
```
### 自定义 CSS 变量
#### 通过 CSS 覆盖
你可以直接在代码中覆盖这些 CSS 变量Button 组件的样式会随之发生改变:
```css
/* 添加这段样式后Primary Button 会变成红色 */
:root {
--van-button-primary-background-color: red;
}
```
#### 通过 ConfigProvider 覆盖
`ConfigProvider` 组件提供了覆盖 CSS 变量的能力,你需要在根节点包裹一个 `ConfigProvider` 组件,并通过 `theme-vars` 属性来配置一些主题变量。
```html
<van-config-provider :theme-vars="themeVars">
<van-form>
<van-field name="rate" label="评分">
<template #input>
<van-rate v-model="rate" />
</template>
</van-field>
<van-field name="slider" label="滑块">
<template #input>
<van-slider v-model="slider" />
</template>
</van-field>
<div style="margin: 16px">
<van-button round block type="primary" native-type="submit">
提交
</van-button>
</div>
</van-form>
</van-config-provider>
```
```js
import { ref } from 'vue';
export default {
setup() {
const rate = ref(4);
const slider = ref(50);
// themeVars 内的值会被转换成对应 CSS 变量
// 比如 sliderBarHeight 会转换成 `--van-slider-bar-height`
const themeVars = {
rateIconFullColor: '#07c160',
sliderBarHeight: '4px',
sliderButtonWidth: '20px',
sliderButtonHeight: '20px',
sliderActiveBackgroundColor: '#07c160',
buttonPrimaryBorderColor: '#07c160',
buttonPrimaryBackgroundColor: '#07c160',
};
return {
rate,
slider,
themeVars,
};
},
};
```
## API
### Props
| 参数 | 说明 | 类型 | 默认值 |
| ---------- | -------------- | -------- | ------ |
| theme-vars | 自定义主题变量 | _object_ | - |