vue

Learn How to create multi-select in Vue


In this article, you are going to learn about how to create multi-select in Vue.

Vue is a modern JavaScript framework that is widely used in building user interfaces and progressive web applications. With Vue you can do lots of eye-catching things but here I will show you how you can build a custom multi-select option with the Vue CDN.

We will create a multi-select option where one can select multiple students’ names from the option and can see the output down below and also remove the names. To do so we need to follow some steps.

Step 1:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Vue Basic</title>
</head>
<body>
  <div id="students">
    <select v-model="mychoice" multiple>
        <option value="Deven">Deven</option>
        <option value="Alex">Alex</option>
        <option value="Smith">Smith</option>
        <option value="Rathore">Rathore</option>
    </select>
    <h1>To Select Multiple hold Ctrl key and Click On The Name:</h1>
    <h1 class="output">{{mychoice}}</h1>
    <button @click="cleardata">Clear Data</button>
</div>

<script src="<https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js>"></script>
<script src="app.js"></script>
  
</body>
</html>

In this HTML file, we have linked vue from CDN and also link our external CSS file and JavaScript file. and finally write the functionality for the multi-select option.

Step 2:

const app = new Vue({
  el: "#students",
  data : {
      mychoice : []
  },
  methods : {
      cleardata(){
          console.log("Clear Data")
          this.mychoice = []
      }
  }
})

In the app.js file, we have written the functionality for showing data and also clearing data. Our selected value will be shown an array.

Output:

multi-select in Vue

You can see that we have selected two values from the option and the output has shown those selected data that was selected by us before.

Important: We have used CSS code to give it a better look. You may style in your own way. Let’s see the functionality for Clear Data button also:

multi-select in Vue
multi-select in Vue

You can see that, the moment we clicked on the Clear Data button our Data from the array has vanished. That means we successfully created a custom multi-select in Vue.


Share on social media

//