Vue Composition API - useToggle
by nolleto
HTML
<script src="https://unpkg.com/vue@next"></script>
<body>
<div id="app">
<my-component />
</div>
</body>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
h2 {
margin-bottom: 8px;
}
JavaScript
const { ref, createApp } = Vue
const app = createApp({});
const useToggle = (initialValue = false) => {
const value = ref(initialValue);
const toggle = () => {
const newValue = !value.value;
value.value = newValue;
};
const setAsTrue = () => {
value.value = true;
};
const setAsFalse = () => {
value.value = false;
};
return { value, toggle, setAsTrue, setAsFalse };
};
app.component('my-component', {
setup() {
const { value: isVisible, toggle: toggleVisibility } = useToggle()
return { isVisible, toggleVisibility }
},
template: `
<div>
<h2>useToggle</h2>
<button @click="toggleVisibility">Toggle visibility</button>
<div v-if="isVisible">
Some content
</div>
</div>
`
})
app.mount("#app");