Switch 开关

引入

  1. import Vue from 'vue';
  2. import { Switch } from 'vant';
  3. Vue.use(Switch);

代码演示

基础用法

通过v-model绑定开关的选中状态,true表示开,false表示关

  1. <van-switch v-model="checked" />
  1. export default {
  2. data() {
  3. return {
  4. checked: true,
  5. };
  6. },
  7. };

禁用状态

通过disabled属性来禁用开关,禁用状态下开关不可点击

  1. <van-switch v-model="checked" disabled />

加载状态

通过loading属性设置开关为加载状态,加载状态下开关不可点击

  1. <van-switch v-model="checked" loading />

自定义大小

通过size属性自定义开关的大小

  1. <van-switch v-model="checked" size="24px" />

自定义颜色

active-color属性表示打开时的背景色,inactive-color表示关闭时的背景色

  1. <van-switch v-model="checked" active-color="#07c160" inactive-color="#ee0a24" />

异步控制

需要异步控制开关时,可以使用value属性和input事件代替v-model,并在input事件回调函数中手动处理开关状态

  1. <van-switch :value="checked" @input="onInput" />
  1. export default {
  2. data() {
  3. return {
  4. checked: true,
  5. };
  6. },
  7. methods: {
  8. onInput(checked) {
  9. Dialog.confirm({
  10. title: '提醒',
  11. message: '是否切换开关?',
  12. }).then(() => {
  13. this.checked = checked;
  14. });
  15. },
  16. },
  17. };

搭配单元格使用

  1. <van-cell center title="标题">
  2. <template #right-icon>
  3. <van-switch v-model="checked" size="24" />
  4. </template>
  5. </van-cell>

API

Props

参数说明类型默认值
v-model开关选中状态anyfalse
loading是否为加载状态booleanfalse
disabled是否为禁用状态booleanfalse
size开关尺寸,默认单位为pxnumber | string30px
active-color打开时的背景色string#1989fa
inactive-color关闭时的背景色stringwhite
active-value打开时对应的值anytrue
inactive-value关闭时对应的值anyfalse

Events

事件名说明回调参数
change开关状态切换时触发value: any
click点击时触发event: Event

Switch 开关 - 图1