JavaScript/jQuery Switch - Getting Started

NOTE
Before you start the tutorial, ensure DevExtreme is installed in your application.

The Switch component allows users to switch between ON (the value is true) and OFF (the value is false) states.

This tutorial shows how to add Switch to a page and configure its core features. The following sample shows the customization result:

Each section in this tutorial describes a single configuration step. You can also find the full source code in the following GitHub repository: getting-started-with-switch.

Create a Switch

Add DevExtreme to your Vue application and use the following code to create a Switch component:

App.vue
  • <template>
  • <DxSwitch>
  • </DxSwitch>
  • </template>
  •  
  • <script>
  • import "devextreme/dist/css/dx.light.css";
  • import { DxSwitch } from "devextreme-vue/switch";
  •  
  • export default {
  • components: {
  • DxSwitch
  • }
  • }
  • </script>

Specify the Initial State

If you need to specify the initial state, assign a Boolean value to the value property. You can also change the Switch component labels. Use the switchedOnText and the switchedOffText properties.

App.vue
  • <template>
  • <DxSwitch
  • :value="false"
  • />
  • </template>
  •  
  • <script>
  • // ...
  • </script>

Configure Size

The component allows you to change its width.

You can also use rtlEnabled property to enable the Right-to-Left layout.

App.vue
  • <template>
  • <DxSwitch ...
  • :width="80"
  • :rtlEnabled="true"
  • />
  • </template>
  •  
  • <script>
  • // ...
  • </script>

Define a Hint

The following code specifies the hint that appears when users hover the mouse pointer over the Switch.

App.vue
  • <template>
  • <DxSwitch ...
  • :hint="hintMessage"
  • @value-changed="onValueChanged"
  • />
  • </template>
  •  
  • <script>
  • import { DxSwitch } from "devextreme-vue/switch";
  • // ...
  •  
  • export default {
  • components: {
  • DxSwitch
  • },
  • data() {
  • return {
  • hintMessage: "Click to switch on",
  • };
  • },
  • methods: {
  • onValueChanged(e) {
  • this.hintMessage = e.value ? "Click to switch off" : "Click to switch on";
  • // ...
  • }
  • }
  • }
  • </script>

Handle Value Change

Users can change a component value (state) with a mouse click, SPACE key, or tap. Implement the onValueChanged callback to handle value changes.

The following code displays a notification every time users change the Switch state:

App.vue
  • <template>
  • <DxSwitch ...
  • @value-changed="onValueChanged"
  • />
  • </template>
  •  
  • <script>
  • // ...
  • import { DxSwitch } from "devextreme-vue/switch";
  • import notify from "devextreme/ui/notify";
  •  
  • export default {
  • components: {
  • DxSwitch
  • },
  • // ...
  • methods: {
  • onValueChanged(e) {
  • // ...
  • const stateLabel = e.value ? "ON" : "OFF";
  • notify(`The component is switched ${stateLabel}`);
  • }
  • }
  • }
  • </script>