Performance: v-model with select dropdowns
This affects how quickly the dropdown updates the UI and how many DOM updates happen when the user selects an option.
<template> <select v-model="selectedId"> <option v-for="item in items" :key="item.id" :value="item.id"> {{ item.name }} </option> </select> </template> <script setup> import { ref, computed } from 'vue' const selectedId = ref(null) const items = ref(Array(1000).fill(0).map((_, i) => ({ id: i, name: `Item ${i}` }))) const selected = computed(() => items.value.find(item => item.id === selectedId.value)) </script>
<template> <select v-model="selected"> <option v-for="item in items" :key="item.id" :value="item"> {{ item.name }} </option> </select> </template> <script setup> import { ref } from 'vue' const selected = ref(null) const items = ref(Array(1000).fill(0).map((_, i) => ({ id: i, name: `Item ${i}` }))) </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Binding full objects as option values | High (many reactive dependencies) | Multiple reflows on selection | High paint cost due to re-renders | [X] Bad |
| Binding primitive IDs as option values | Low (simple reactive refs) | Single reflow on selection | Low paint cost | [OK] Good |
v-model do when used on a <select> dropdown in Vue?v-model to a <select> element in Vue?v-model="selectedOption". Others misuse binding or add invalid characters.<select v-model="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
<p>Selected: {{ fruit }}</p>value attribute is "banana" (lowercase), label is "Banana" (capitalized).fruit becomes "banana" (the value attribute).<select v-model="selected"> <option>One</option> <option value="two">Two</option> <option value="three">Three</option> </select>
selected is initially "two", what issue will occur?value attribute, so its value defaults to its text content "One".selected is "two", Vue tries to match it with option values. It matches the second option, but the first option's missing value can cause confusion or unexpected behavior.v-model in Vue. Which is the correct way to bind the <select> element to an array of selected values?multiple attribute is added without a value or with boolean true.selectedFruits works. Adding brackets or setting multiple as a string is incorrect.Pass the test and this pattern moves unknown