Scenario
I am currently developing a personalized filtering feature. This feature allows users to add n
filters that are shown using a v-for
loop in the template. Users have the ability to modify input values and remove filters as needed.
Challenge
Issue arises when removing a filter, where my array itemRefs
ends up with a null
value for the last item.
Code (simplified)
<script setup>
const filtersScope = $ref([])
const itemRefs = $ref([])
function addFilter () {
filtersScope.push({ value: '' })
}
function removeFilter (idx) {
filtersScope.splice(idx, 1)
itemRefs.pop() // <- necessary? has no effect
// validate and emit stuff
console.log(itemRefs)
// itemRefs got at least one null item
// itemRefs = [null]
}
// assigning values from input fields for future use
function updateValue() {
itemRefs.forEach((input, idx) => filtersScope[idx].value = input.value)
}
</script>
<template>
<div v-for="(filter, idx) in filtersScope" :key="filter.id">
<input
type="text"
@keyup="updateValue"
:ref="(input) => { itemRefs[idx] = input }"
:value="filter.value"
>
<button @click="removeFilter(idx)" v-text="'x'" />
</div>
<button @click="addFilter()" v-text="'add filter +'" />
</template>
>>> View Demo
to replicate:
- Add two filters
itemRefs
will now store the template refs as follows:[input, input]
- Remove one filter, resulting in
itemRefs
looking like:[input, null]
- Remove the last filter, leaving
itemRefs
as:[null]
Inquiry
Even after adding itemRefs.pop()
, I encountered an error when applying new filters after removal:
Uncaught TypeError: input is null
While the pop()
method prevented a console error, the inclusion of null
in itemRefs
still persists.
How can I properly clean up my template references?