Skip to content

Switch 开关

switch

规则

基础示例

js
const rule = {
    type: 'switch',
    title: '开关',
    field: 'switch',
    value: 1,
    props: {
        activeValue: 1,
        inactiveValue: 0
    }
}

Props 配置示例

自定义颜色

js
const rule = {
    type: 'switch',
    title: '商品状态',
    field: 'status',
    value: true,
    props: {
        activeValue: true,
        inactiveValue: false,
        activeColor: '#07c160',
        inactiveColor: '#ee0a24',
    }
}

自定义尺寸

js
const rule = {
    type: 'switch',
    title: '通知开关',
    field: 'notification',
    value: true,
    props: {
        size: '24px',
    }
}

加载状态

js
const rule = {
    type: 'switch',
    title: '自动保存',
    field: 'autoSave',
    value: false,
    props: {
        loading: false,
    }
}

Events 事件示例

监听开关变化

js
const rule = {
    type: 'switch',
    title: '是否上架',
    field: 'is_show',
    value: 1,
    props: {
        activeValue: 1,
        inactiveValue: 0,
    },
    on: {
        change: (value) => {
            console.log('开关状态改变:', value);
        },
        click: (event) => {
            console.log('点击开关:', event);
        },
    },
}

联动更新其他字段

js
const rule = [
    {
        type: 'switch',
        title: '启用折扣',
        field: 'enableDiscount',
        value: false,
        props: {
            activeValue: true,
            inactiveValue: false,
        },
        inject: true,
        on: {
            change: ($inject, value) => {
                // 启用折扣时,自动设置默认折扣率
                if (value) {
                    $inject.api.setValue('discount', 0.9);
                } else {
                    $inject.api.setValue('discount', 1);
                }
            },
        },
    },
    {
        type: 'stepper',
        title: '折扣率',
        field: 'discount',
        props: {
            min: 0,
            max: 1,
            step: 0.1,
            decimalLength: 2,
            disabled: false,
        },
    },
]

完整配置项:Vant_Switch

value :Number | String | Boolean

Props

参数说明类型默认值
loading是否为加载状态booleanfalse
disabled是否为禁用状态booleanfalse
size开关按钮的尺寸,默认单位为 pxnumber | string26px
active-color打开时的背景色string#1989fa
inactive-color关闭时的背景色stringrgba(120, 120, 128, 0.16)
active-value打开时对应的值anytrue
inactive-value关闭时对应的值anyfalse

Events

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

FormCreate 是一个开源项目,基于 MIT 许可证发布,欢迎个人和企业用户免费使用