How To Create Toggle Button In Vue.js

In this article, I will guide you on how to create Toggle button in Vue.js

Prerequisites

  • node.js installed
  • Tailwind CSS

You can check how to install Tailwind CSS in vue.js from the below link

Create Vue.js Project

To create a Vue.js app, use the following command in the terminal.

vue create tailwindcss

Install daisyUI

Install daisyUI using following npm command

npm i daisyui

Open tailwind.config.js and add following code.

module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [require("daisyui")],
}

Now right-click on the components folder and add a new component named 'toggledemo.vue'. Now open toggledemo.vue component and add the following code. 

<template>
    <div class="form-control">
        <label class="label cursor-pointer">
            <span class="label-text">Remember me</span>
            <input type="checkbox" class="toggle toggle-primary" checked />
        </label>
    </div>
</template>
    
<script>
export default {
    name: 'toggledemo',
    props: {
        msg: String
    }
}
</script>  
  
<style scoped>
h3 {
    margin: 40px 0 0;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}
</style>

Now open App.vue component. Add the following code in App.vue component.

<template>
  <div id="app">
    <toggledemo />
  </div>
</template>
<script>

import toggledemo from './components/toggledemo.vue'
export default {
  name: 'App',
  components: {
    toggledemo
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

Now run the application by using following command.

npm run serve

Add the following code in toggledemo.vue component.

<template>
    <div class="form-control">
        <input type="checkbox" class="toggle toggle-xs" checked />
        <input type="checkbox" class="toggle toggle-sm" checked />
        <input type="checkbox" class="toggle toggle-md" checked />
        <input type="checkbox" class="toggle toggle-lg" checked />
    </div>
</template>  
  
<script>
export default {
    name: 'toggledemo',
    props: {
        msg: String
    }
}
</script>  
  
<style scoped>
h3 {
    margin: 40px 0 0;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}
</style>

Summary

 In this article, we learned how to Create Toggle button in Vue.js