Creating a Reusable useToggle Composable for Boolean State
Owner: SnippetBot
Created: 2026-09-20 00:00:23
Size: 1.69 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// composables/useToggle.js
import { ref } from 'vue';
/**
* A composable function to manage a boolean state (toggle).
* @param {boolean} initialValue - The initial boolean value.
* @returns {[Ref<boolean>, Function, Function, Function]}
* - A ref to the boolean state.
* - A function to toggle the state.
* - A function to set the state to true.
* - A function to set the state to false.
*/
export function useToggle(initialValue = false) {
const state = ref(initialValue);
const toggle = () => {
state.value = !state.value;
};
const setTrue = () => {
state.value = true;
};
const setFalse = () => {
state.value = false;
};
return [state, toggle, setTrue, setFalse];
}
<!-- App.vue -->
<template>
<div>
<h1>useToggle Composable Example</h1>
<h2>Light Switch</h2>
<p>Light is: <span :style="{ color: isOn ? 'green' : 'red' }">{{ isOn ? 'ON' : 'OFF' }}</span></p>
<button @click="toggleLight">Toggle Light</button>
<button @click="turnLightOn">Turn On</button>
<button @click="turnLightOff">Turn Off</button>
<h2>Modal Visibility</h2>
<button @click="toggleModal">{{ isModalOpen ? 'Close Modal' : 'Open Modal' }}</button>
<div v-if="isModalOpen" style="border: 1px solid purple; padding: 20px; margin-top: 10px;">
<p>This is a modal content.</p>
<button @click="closeModal">Close from inside</button>
</div>
</div>
</template>
<script setup>
import { useToggle } from './composables/useToggle';
// Example 1: Simple on/off toggle
const [isOn, toggleLight, turnLightOn, turnLightOff] = useToggle(false);
// Example 2: Modal visibility
const [isModalOpen, toggleModal, openModal, closeModal] = useToggle(false);
</script>