Skip to content

Switch 开关

表示两种相互对立的状态间的切换,多用于触发「开/关」。

引入

html
<script type="module">
  import "./node_modules/easy-component-ui/dist/components/ea-switch.js";
</script>
js
import "easy-component-ui/ea-switch";

自定义样式

移步到 CSS PartCSS Custom Properties

基础用法

查看代码
html
<div class="demo">
  <ea-switch name="basic" value="true"></ea-switch>
  <ea-switch
    name="basicHasText"
    value="true"
    style="
          --ea-switch-active-bg-color: #13ce66;
          --ea-switch-inactive-bg-color: #ff4949;
        "
  ></ea-switch>
</div>

不同尺寸

提供 largedefaultsmall 三种尺寸,通过 size 属性设置。



查看代码
html
<div class="demo">
  <ea-switch
    name="basic"
    value="true"
    size="large"
    active-text="Open"
    inactive-text="Close"
  ></ea-switch>
  <br />
  <ea-switch
    name="basic"
    value="true"
    active-text="Open"
    inactive-text="Close"
  ></ea-switch>
  <br />
  <ea-switch
    name="basic"
    value="true"
    size="small"
    active-text="Open"
    inactive-text="Close"
  ></ea-switch>
</div>

文字描述

使用 active-text 属性与 inactive-text 属性来设置开关的文字描述,也可通过 activeinactive 插槽自定义内容。



查看代码
html
<div class="demo">
  <ea-switch
    value="true"
    active-text="Pay by month"
    inactive-text="Pay by year"
  ></ea-switch>
  <br />
  <ea-switch
    value="true"
    active-text="Pay by month"
    inactive-text="Pay by year"
    style="
          --ea-switch-active-bg-color: #13ce66;
          --ea-switch-inactive-bg-color: #ff4949;
        "
  ></ea-switch>
  <br />
  <ea-switch
    value="true"
    style="
          --ea-switch-active-bg-color: #13ce66;
          --ea-switch-inactive-bg-color: #ff4949;
        "
  >
    <ea-icon name="ban" slot="inactive"></ea-icon>
    <ea-icon name="check" slot="active"></ea-icon>
  </ea-switch>
</div>

扩展的 value 类型

你可以设置 active-valueinactive-value 属性,它们接受 BooleanStringNumber 类型的值。

查看代码
html
<div class="demo">
  <ea-tooltip id="extTooltip" content="1111" placement="top-start">
    <ea-switch
      id="extSwitch"
      slot="reference"
      value="100"
      style="
            --ea-switch-active-bg-color: #13ce66;
            --ea-switch-inactive-bg-color: #ff4949;
          "
      active-value="100"
      inactive-value="0"
    ></ea-switch>
  </ea-tooltip>
</div>
js
const extExample = {
  tooltip: document.querySelector("#extTooltip"),
  switch: document.querySelector("#extSwitch"),

  init() {
    const getContentString = value =>
      `Switch value: ${value === 100 ? "100" : "0"}`;

    this.tooltip.setAttribute("content", getContentString(this.switch.value));

    this.switch.addEventListener("change", e => {
      this.tooltip.setAttribute("content", getContentString(e.detail.value));
    });
  },
};
extExample.init();

禁用状态

设置 disabled 属性即可禁用开关。

查看代码
html
<div class="demo">
  <ea-switch disabled></ea-switch>
  <ea-switch
    value="true"
    active-text="Pay by month"
    inactive-text="Pay by year"
    disabled
  ></ea-switch>
</div>

阻止切换

设置 beforeChange 属性,在切换前进行拦截。返回 Promise.resolve() 允许切换,返回 Promise.reject() 阻止切换。

查看代码
html
<div class="demo">
  <ea-switch id="forbiddenSwitch1"></ea-switch>
  <ea-switch id="forbiddenSwitch2"></ea-switch>
</div>
js
const forbiddenExample = {
  switch1: document.querySelector("#forbiddenSwitch1"),
  switch2: document.querySelector("#forbiddenSwitch2"),

  init() {
    this.switch1.beforeChange = () => {
      this.switch1.toggleAttribute("disabled", true);

      return new Promise(resolve => {
        setTimeout(() => {
          this.switch1.toggleAttribute("disabled", false);
          window.$message.success("Switch success");
          return resolve(true);
        }, 1000);
      });
    };

    this.switch2.beforeChange = () => {
      this.switch2.toggleAttribute("disabled", true);

      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.switch2.toggleAttribute("disabled", false);
          window.$message.error("Switch failed");
          return reject(new Error("Error"));
        }, 1000);
      });
    };
  },
};
forbiddenExample.init();

Switch API

Switch Attributes

参数说明类型可选值默认值
label标签文本string''
name原生属性,若与 form 组合使用,则作为 FormData 的键名string''
value当前开关的值string / number / booleanfalse
activeValue打开时的值string / number / booleantrue
inactiveValue关闭时的值string / number / booleanfalse
size开关的尺寸stringlarge | default | smalldefault
inactiveText关闭时显示的文字string''
inactiveColor关闭时的背景色string''
activeText打开时显示的文字string''
activeColor打开时的背景色string''
disabled是否禁用booleanfalse
required是否必填booleanfalse
beforeChange prop切换前的回调函数,返回 PromiseFunctionnull

Switch CSS Part

用法可参考 MDN ::part()伪类

名称说明
wrapper外层 label 容器
label表单标签
form-label表单标签(与 label 相同)
container开关内容容器
original原生 checkbox 控件
label-left左侧文字(关闭状态)
switch伪开关控件
label-right右侧文字(打开状态)

Switch Slots

名称说明
active打开状态时的内容
inactive关闭状态时的内容

Switch Methods

方法名说明参数
updateContainerClasslist更新容器类名
checkValidity检查表单字段的有效性
reportValidity报告表单字段的有效性

Switch Events

事件名说明回调参数 ( event.detail )
change状态发生变化时触发{ value: String | Number | Boolean }

Switch CSS Custom Properties

属性名说明默认值
--ea-switch-active-bg-color打开时的背景色var(--blue-500)
--ea-switch-inactive-bg-color关闭时的背景色var(--grey-300)
--ea-switch-active-text-color打开时的文字颜色var(--blue-500)
--ea-switch-inactive-text-color关闭时的文字颜色var(--grey-900)
--ea-switch-disabled-bg-color禁用时的背景色var(--grey-200)
--ea-switch-disabled-text-color禁用时的文字颜色var(--grey-300)
--ea-switch-disabled-checked-bg-color禁用且选中时的背景色var(--blue-300)
--ea-switch-disabled-checked-text-color禁用且选中时的文字颜色var(--blue-300)

类型支持

组件提供完整的 TypeScript 类型声明文件,支持 HTML、Vue 和 React 的类型提示。

HTML

组件支持 HTMLElementTagNameMap 扩展:

typescript
const switchEl = document.createElement("ea-switch");
switchEl.value = true; // 类型安全
switchEl.activeValue = "yes";
switchEl.size = "large";

Vue

组件支持 Vue 全局组件类型:

typescript
// 在模板中使用时有类型提示
<ea-switch :value="true" active-text="On" @change="handleChange" />

React

组件支持 JSX 类型:

typescript
// 在 JSX 中使用时有类型检查
<ea-switch value={true} activeText="On" onChange={handleChange} />