Phil's Notes

Adding and Removing Items from a Multiple Select List with Vue.js

vue

First, we create the html page. I just named this one index.html. Over in line 7, we are including the Vue.js framework in our page. In the body, we have a div with the class "vue-app" which we will define later in a file called app.js where we will keep our Vue app code.

In line 12, we create an input box and bind it to "listItem". This array will hold all the items we enter. Right underneath that, we add a button which will call the addToList() function in app.js when it is clicked.

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<link href="styles.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
</head>

<body>
<div id="vue-app">
<input type="text" v-model="listItem">
<button v-on:click="addToList()">Enter</button>

<select multiple>
<option v-for="(item, index) in list" value=""
v-on:dblclick="removeFromList(index)">

</option>
</select>
</div>

<script src="app.js"></script>
</body>

</html>
select {
display: block;
}
new Vue({
el: '#vue-app',
data: {
listItem: '',
list: []
},
methods: {
addToList: function() {
console.log(`Adding ${this.listItem} to list`);
this.list.push(this.listItem);
this.listItem = '';
},
removeFromList: function(index) {
console.log(`Removing element from index ${index}`);
this.list.splice(index, 1);
}
}
});