Performance: v-model with checkboxes
This affects how user input updates the UI and how Vue tracks checkbox states, impacting interaction responsiveness and rendering.
<template> <input type="checkbox" :value="item" v-model="selected" /> </template> <script setup> import { ref } from 'vue'; const selected = ref([]); </script>
<template> <input type="checkbox" :value="item" @change="updateSelection($event, item)" /> </template> <script setup> import { ref } from 'vue'; const selected = ref([]); function updateSelection(event, item) { if (event.target.checked) { selected.value.push(item); } else { selected.value = selected.value.filter(i => i !== item); } } </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual @change handler | Multiple array mutations and DOM updates | Multiple reflows per toggle | High paint cost due to repeated updates | [X] Bad |
| v-model binding | Single reactive update per toggle | Single reflow per toggle | Minimal paint cost | [OK] Good |
v-model when binding to multiple checkboxes in Vue?v-model, Vue expects an array to store all selected values.v-model in Vue?v-model directive binds the checkbox's checked state to a data property.<input type='checkbox' v-model='checked' /> uses v-model='checked' which is the correct and simplest syntax for binding a single checkbox.<template>
<input type='checkbox' v-model='selected' value='apple' />
<input type='checkbox' v-model='selected' value='banana' />
<input type='checkbox' v-model='selected' value='cherry' />
<p>Selected: {{ selected }}</p>
</template>
<script setup>
import { ref } from 'vue'
const selected = ref([])
</script>v-model bound to an array, Vue adds the checkbox's value to the array when checked.<input type='checkbox' v-model='checked' value='yes' />
<script setup>
import { ref } from 'vue'
const checked = ref(false)
</script>checked?checked is a boolean, so Vue treats the checkbox as a single toggle (true/false).v-model is boolean, the value attribute is ignored; it only matters when binding to an array.v-model. The data property is favorites initialized as an empty array. Which code snippet correctly updates favorites when users check or uncheck fruits?v-model and distinct value attributes collects checked values in the array.<input type='checkbox' v-model='favorites' value='apple' />
<input type='checkbox' v-model='favorites' value='banana' />
<input type='checkbox' v-model='favorites' value='cherry' /> correctly uses v-model='favorites' with unique string values for each checkbox, so checked fruits are added or removed from the array.Pass the test and this pattern moves unknown