Toggle buttons are a common UI element used to switch between two states, like on/off, active/inactive, or enabled/disabled. In this article, we’ll create a modern, functional toggle button using Vue 3’s Composition API with clean, reusable code.
Step 1: Setting Up the ToggleButton Component
<template>
<button
:class="['toggle-button', { active: isActive }]"
@click="toggle"
>
{{ isActive ? 'ON' : 'OFF' }}
</button>
</template>
<script setup>
import { ref } from 'vue';
// Reactive state for toggle
const isActive = ref(false);
// Toggle function
const toggle = () => {
isActive.value = !isActive.value;
};
</script>
<style scoped>
.toggle-button {
padding: 10px 20px;
background-color: #ddd;
border: none;
border-radius: 20px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s;
font-weight: bold;
color: #333;
}
.toggle-button.active {
background-color: #4caf50;
color: white;
transform: scale(1.05);
}
.toggle-button:hover {
background-color: #bbb;
}
</style>
How It Works:
- Reactive State with
ref(): - We use
ref(false)to create a reactiveisActiveproperty, representing the toggle’s state. - Toggle Function:
- The
togglemethod inverts theisActivestate whenever the button is clicked. - Dynamic Classes:
- The button’s style changes based on the
isActivestate using Vue’s class binding syntax:
:class="['toggle-button', { active: isActive }]"
- Smooth Transitions:
- CSS transitions provide a modern feel when the toggle state changes.
Using the ToggleButton Component
You can import and use this component anywhere in your Vue app:
<template> <ToggleButton /> </template> <script setup> import ToggleButton from './components/ToggleButton.vue'; </script>