Switch 开关

开关选择器。

何时使用

  • 需要表示开关状态/两种状态之间的切换时;
  • checkbox的区别是,切换 switch 会直接触发状态改变,而 checkbox 一般用于状态标记,需要和提交操作配合。

代码演示

Switch开关 - 图1

基本用法

最简单的用法。

  1. <template>
  2. <div>
  3. <a-switch defaultChecked @change='onChange'/>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data () {
  9. return {
  10. }
  11. },
  12. methods: {
  13. onChange(checked){
  14. console.log(`a-switch to ${checked}`);
  15. }
  16. },
  17. }
  18. </script>

Switch开关 - 图2

不可用

Switch 失效状态。

  1. <template>
  2. <div>
  3. <a-switch defaultChecked :disabled="disabled" style="margin-bottom:5px"/>
  4. <br/>
  5. <a-button type="primary" @click='onToggle'>Toggle disabled</a-button>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. data () {
  11. return {
  12. disabled: true,
  13. }
  14. },
  15. methods: {
  16. onToggle(){
  17. this.disabled = !this.disabled
  18. }
  19. },
  20. }
  21. </script>

Switch开关 - 图3

文字和图标

带有文字和图标。

  1. <template>
  2. <div>
  3. <a-switch checkedChildren="开" unCheckedChildren="关" defaultChecked/>
  4. <br>
  5. <a-switch checkedChildren="1" unCheckedChildren="0"/>
  6. <br>
  7. <a-switch defaultChecked >
  8. <a-icon type="check" slot="checkedChildren"/>
  9. <a-icon type="close" slot="unCheckedChildren"/>
  10. </a-switch>
  11. </div>
  12. </template>

Switch开关 - 图4

两种大小

size="small" 表示小号开关。

  1. <template>
  2. <div>
  3. <a-switch defaultChecked/>
  4. <br>
  5. <a-switch size="small" defaultChecked/>
  6. </div>
  7. </template>

Switch开关 - 图5

加载中

标识开关操作仍在执行中。

  1. <template>
  2. <div>
  3. <a-switch loading defaultChecked/>
  4. <br>
  5. <a-switch size="small" loading/>
  6. </div>
  7. </template>

API

参数说明类型默认值
autoFocus组件自动获取焦点booleanfalse
checked(v-model)指定当前是否选中booleanfalse
checkedChildren选中时的内容string|slot
defaultChecked初始是否选中booleanfalse
disabled是否禁用booleanfalse
loading加载中的开关booleanfalse
size开关大小,可选值:default smallstringdefault
unCheckedChildren非选中时的内容string|slot

事件

事件名称说明回调参数
change变化时回调函数Function(checked:Boolean)

方法

名称描述
blur()移除焦点
focus()获取焦点