Back to Vant Weapp

Switch 开关

packages/switch/README.md

1.11.72.5 KB
Original Source

Switch 开关

介绍

用于在打开和关闭状态之间进行切换。

引入

app.jsonindex.json中引入组件,详细介绍见快速上手

json
"usingComponents": {
  "van-switch": "@vant/weapp/switch/index"
}

代码演示

基础用法

html
<van-switch checked="{{ checked }}" bind:change="onChange" />
javascript
Page({
  data: {
    checked: true,
  },

  onChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ checked: detail });
  },
});

禁用状态

html
<van-switch checked="{{ checked }}" disabled />

加载状态

html
<van-switch checked="{{ checked }}" loading />

自定义大小

html
<van-switch checked="{{ checked }}" size="24px" />

自定义颜色

html
<van-switch
  checked="{{ checked }}"
  active-color="#07c160"
  inactive-color="#ee0a24"
/>

异步控制

html
<van-switch checked="{{ checked }}" bind:change="onChange" />
js
Page({
  data: {
    checked: true,
  },

  onChange({ detail }) {
    wx.showModal({
      title: '提示',
      content: '是否切换开关?',
      success: (res) => {
        if (res.confirm) {
          this.setData({ checked2: detail });
        }
      },
    });
  },
});

API

Props

参数说明类型默认值
name在表单内提交时的标识符string-
checked开关选中状态anyfalse
loading是否为加载状态booleanfalse
disabled是否为禁用状态booleanfalse
size开关尺寸string30px
active-color打开时的背景色string#1989fa
inactive-color关闭时的背景色string#fff
active-value打开时的值anytrue
inactive-value关闭时的值anyfalse

Events

事件名说明参数
bind:change开关状态切换回调event.detail: 是否选中开关

外部样式类

类名说明
custom-class根节点样式类
node-class圆点样式类