Create a Dynamic Toggle Button with
Vue.js : A toggle button is a
user interface element that enables users to switch between two states, such as “on” and “off”. Vue.js can be used to create a toggle button by incorporating HTML, CSS, and JavaScript. In this guide, we’ll learn how to make a toggle button with the help of Vue.js. Vue.js provides an uncomplicated way to create a toggle button using its framework. It generates a button with dynamic text that alternates between “ON” and “OFF” every time the button is clicked. The text displayed on the button is controlled by the isActive property, which is managed by the Vue instance. Whenever the button is clicked, the toggle method is invoked and it changes the value of isActive between true and false.
How to Implement Toggle Button in Vue Js?
- The HTML code creates a div with an id of “app” and a button element within it.
- The button element has a
@click
directive that binds to a method named “toggle”. - The text within the button is dynamic and is determined by the computed property “text”.
- The JavaScript code starts with importing the
createApp
function from the Vue library. - The
createApp
function is called with an object that contains:- A
data
function that returns an object with the property “isActive” set tofalse
. - A
computed
property that returns an object with the “text” property. The “text” property returns either ‘ON’ or ‘OFF’ depending on the value ofisActive
. - A
methods
property that contains a “toggle” method that switches the value ofisActive
fromtrue
tofalse
or vice versa.
- A
Vue Js Dynamic Text of the Toggle Button
<div id="app">
<button @click="toggle">{{ text }}</button>
</div>
<script type="module">
import { createApp } from "vue";
createApp({
data() {
return {
isActive: false,
}
},
computed: {
text() {
return this.isActive ? 'ON' : 'OFF';
},
},
methods: {
toggle() {
this.isActive = !this.isActive;
},
},
}).mount("#app");
</script>