Prevent State Change in Vue Switch component

14 Dec 20242 minutes to read

The beforeChange event is triggered before the switch’s state is altered. This event provides an opportunity to intercept and potentially cancel the change action before it is applied. It allows for implementing conditional logic or validating the change prior to it being rendered on the UI.

<template>
    <div>
        <!-- Use v-bind:checked or :checked for dynamic binding, and note that true should be lowercase -->
        <ejs-switch id="switch1" :checked="true" @beforeChange="beforeChange"></ejs-switch>
    </div>
</template>

<script setup>
import { SwitchComponent as EjsSwitch } from "@syncfusion/ej2-vue-buttons";
import { enableRipple } from '@syncfusion/ej2-base';

enableRipple(true);

function beforeChange(args) {
    // Set cancel to true to prevent the switch state change
    args.cancel = true;
}
</script>

<style>
@import "../node_modules/@syncfusion/ej2-base/styles/fabric.css";
@import "../node_modules/@syncfusion/ej2-buttons/styles/fabric.css";
</style>
<template>
    <div>
        <ejs-switch id="switch1" :checked="true" :beforeChange="beforeChange"></ejs-switch>
    </div>
</template>

<script>
import { SwitchComponent } from "@syncfusion/ej2-vue-buttons";
import { enableRipple } from '@syncfusion/ej2-base';

enableRipple(true);

export default {
    name: "App",
    components: {
        "ejs-switch": SwitchComponent
    },
    methods: {
        beforeChange(args) {
            // Set cancel to true to prevent the switch state change
            args.cancel = true;
        }
    }
}
</script>

<style>
@import "../node_modules/@syncfusion/ej2-base/styles/fabric.css";
@import "../node_modules/@syncfusion/ej2-buttons/styles/fabric.css";
</style>