How To Use Checkbox In Vue.js?

Introduction

In this article, we are going to learn how to work with Checkbox in Vue.js.

Prerequisites

  • We should have basic knowledge of HTML and Vue.js.
  • Visual Studio Code editor

Create VueJS Project

Create a Vue.js project by using the following command.

vue create multiselecrdropdown

Now open this project in Vs code and install bootstrap.

npm install bootstrap-vue bootstrap --save

Now open the main.js file and import bootstrap reference.

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

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

<template>
    <div class="row" style="margin:10px">
      <div class="col-sm-12 btn btn-info"> How To Use Checkbox In Vue.Js </div>
    </div>
    <input
      type="checkbox"
      id="checkboxvalue"
      value="checkboxvalue"
      name="checkboxvalue"
      v-model="checkboxvalue"
    />
    <label for="apple">Check</label><br />
  
    <p>Checked: {{ checkboxvalue  }}</p>
  </template>

<script>

export default {
  
    name: 'Checkboxdemo',
    data() {
    return {
        checkboxvalue: null,
    };
  },
  
}
</script>

Now open App.vue component and import the checkboxdemo component. add the following code in App.vue component.

<template>
  <Checkboxdemo />
</template>
<script>
import Checkboxdemo from './components/Checkboxdemo.vue'
export default {
  components: {
    'Checkboxdemo': Checkboxdemo
  }
};
</script>

Now run the application by using 'npm run serve' command and check.

Single Checkbox

Multiple Checkbox

Now we will create multiple checkboxes , add the following code in the checkboxdemo  component.

<template>
    <input
      type="checkbox"
      id="delhi"
      value="delhi"
      name="delhi"
      v-model="cities"
    />
    <label for="delhi">Delhi</label><br />
    <input
      type="checkbox"
      id="noida"
      value="noida"
      name="noida"
      v-model="cities"
    />
    <label for="noida">Noida</label><br />
    <input
      type="checkbox"
      id="jaipur"
      value="jaipur"
      name="jaipur"
      v-model="cities"
    />
    <label for="jaipur">Jaipur</label><br />
    <p>Selected Checkbox Values: {{ cities }}</p>
  </template>

<script>

export default {
  
    name: 'Checkboxdemo',
    data() {
    return {
        cities: [],
    };
  },
  
}
</script>

Now run the project and check the result.

Multiple Checkboxes

Summary

In this article, we learned how we use Checkbox   in Vue.js applications