Skip to content

Switch

switch

Rule

Basic Example

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

Props Configuration Examples

Custom Color

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

Custom Size

js
const rule = {
    type: 'switch',
    title: 'Notification Switch',
    field: 'notification',
    value: true,
    props: {
        size: '24px',
    }
}

Loading State

js
const rule = {
    type: 'switch',
    title: 'Auto Save',
    field: 'autoSave',
    value: false,
    props: {
        loading: false,
    }
}

Events Examples

Handle Switch Changes

js
const rule = {
    type: 'switch',
    title: 'Is Listed',
    field: 'is_show',
    value: 1,
    props: {
        activeValue: 1,
        inactiveValue: 0,
    },
    on: {
        change: (value) => {
            console.log('Switch state changed:', value);
        },
        click: (event) => {
            console.log('Switch clicked:', event);
        },
    },
}

Linkage Update Other Fields

js
const rule = [
    {
        type: 'switch',
        title: 'Enable Discount',
        field: 'enableDiscount',
        value: false,
        props: {
            activeValue: true,
            inactiveValue: false,
        },
        inject: true,
        on: {
            change: ($inject, value) => {
                // Auto-set default discount rate when discount is enabled
                if (value) {
                    $inject.api.setValue('discount', 0.9);
                } else {
                    $inject.api.setValue('discount', 1);
                }
            },
        },
    },
    {
        type: 'stepper',
        title: 'Discount Rate',
        field: 'discount',
        props: {
            min: 0,
            max: 1,
            step: 0.1,
            decimalLength: 2,
            disabled: false,
        },
    },
]

Complete configuration items:Vant_Switch

value :Number | String | Boolean

Props

ParameterDescriptionTypeDefault Value
loadingWhether it is in loading statebooleanfalse
disabledWhether it is in disabled statebooleanfalse
sizeSwitch button size, default unit is pxnumber | string26px
active-colorBackground color when onstring#1989fa
inactive-colorBackground color when offstringrgba(120, 120, 128, 0.16)
active-valueValue when onanytrue
inactive-valueValue when offanyfalse

Events

Event NameDescriptionCallback Parameters
changeTriggered when switch state changesvalue: any
clickTriggered when clickedevent: MouseEvent

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.