點燈坊

失くすものさえない今が強くなるチャンスよ

Data Binding with Listbox

Sam Xiao's Avatar 2022-01-06

We can implement data binding with <select> for listbox by v-for.

Version

Vue 3.2

Listbox

listbox000

  • Listbox is bound to data
  • We can add a new item to data and display the new item on listbox
  • We can select the item on listbox and delete the item
<script setup>
import { ref } from 'vue'

let newItem = ref('')

let colors = ref([
  { title: 'Red', value: 'red' },
  { title: 'Green', value: 'green' },
  { title: 'Blue', value: 'blue' }
])

let selectedItem = ref('')

let onAdd = () => {
  colors.value.push({
    title: newItem,
    value: newItem.value.toLowerCase()
  })
}

let onDel = () => {
  colors.value = colors.value.filter(x => x.value !== selectedItem.value)
}
</script>

<template>
  <div>
    <input type="text" v-model="newItem">
    <button @click="onAdd">Add</button>
  </div>
  <div>
    <select size="5" v-model="selectedItem">
      <option v-for="x in colors" :value="x.value">{{ x.title }}</option>
    </select>
  </div>
  <div>
    <button @click="onDel">Delete selected</button>
  </div>
</template>

Line 28

<input type="text" v-model="newItem">
<button @click="onAdd">Add</button>

Add new item to listbox.

Line 32

<select size="5" v-model="selectedItem">
  <option v-for="x in colors" :value="x.value">{{ x.title }}</option>
</select>

Display all items on listbox :

  • We have to add size attribute to make <select> to listbox or <select> will become dropdown list
  • v-for : bind data to <option>

Line 37

<button @click="onDel">Delete selected</button>

Delete selected item on listbox.

Line 4

let newItem = ref('')

Define newItem to bind to <input>.

Line 6

let colors = ref([
  { title: 'Red', value: 'red' },
  { title: 'Green', value: 'green' },
  { title: 'Blue', value: 'blue' }
])

Define colors to bind to listbox.

Line 12

let selectedItem = ref('')

Define selectedItem to bind to selected item for listbox.

Line 14

let onAdd = () => {
  colors.value.push({
    title: newItem,
    value: newItem.value.toLowerCase()
  })
}

Push new item to data.

Line 21

let onDel = () => {
  colors.value = colors.value.filter(x => x.value !== selectedItem.value)
}

Reject the selected item to delete an item in Data.

Conclusion

  • <select> with size attribute will make <select> to listbox