Skip to content

Switch 开关

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

引入

js

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

css

TIP

需要注意的是, 如果需要使用到带有图标的 属性/组件, 需要提前使用 link 标签引入图标文件

html
<link
  rel="stylesheet"
  href="./node_modules/easy-component-ui/components/ea-icon/index.css"
/>

自定义样式

移步到 CSS Part

基本用法

查看代码
html
<div class="row">
  <ea-switch></ea-switch>
  <ea-switch inactive-text="按年付费" active-text="按月付费"></ea-switch>
</div>

默认选中状态

查看代码
html
<div class="row">
  <ea-switch checked></ea-switch>
  <ea-switch
    inactive-text="按年付费"
    active-text="按月付费"
    checked
  ></ea-switch>
</div>

禁用状态

查看代码
html
<div class="row">
  <ea-switch disabled></ea-switch>
  <ea-switch
    inactive-text="按年付费"
    active-text="按月付费"
    checked
    disabled
  ></ea-switch>
</div>

指定背景色

查看代码
html
<div class="row">
  <ea-switch inactive-color="#ff4949" active-color="#13ce66"></ea-switch>
  <ea-switch
    inactive-color="#ff4949"
    active-color="#13ce66"
    inactive-text="按年付费"
    active-text="按月付费"
    checked
  ></ea-switch>
</div>

change 事件

查看代码

是否选中: e.detail.checked

选中值: e.detail.value

js
document.querySelector("#switch").addEventListener("change", function (e) {
  console.log(e.detail.checked, e.detail.value);
});

Attributes

参数说明类型可选值默认值
checked是否选中Boolean-false
disabled是否禁用Boolean-false
active-color选中时的背景色String-#1989fa
inactive-color未选中时的背景色String-#dcdfe6
active-text选中时的文字String--
inactive-text未选中时的文字String--

CSS Part

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

名称说明
container外层容器
label-left左侧文字
switch开关
label-right右侧文字

Events

事件名说明回调参数
change状态发生变化时触发(e.detail.checked: Boolean, e.detail.value: String)