So I Have this loop of inputs(code below :)). So basically I'm trying to get every input in that loop by a unique ref like its explained in Vue3 documentations => Here
I have this Array inputs
where I'm saving all inputs like documentations suggest. what I want to achieve here is getting the last value. But I'm facing a strange issue that's why I'm here.
So when I try to console.log
the last value of that array I get the before last one not the last(I'll explain with image for more comprehension).and when I console.log
the inputs
array I can see that it contains the last value but I cant get it with all methods I tried:
console.log(inputs.value[inputs.value.length-1])
console.log(inputs.value.at(-1))
html code:
<n-card v-for="(item, index) in counter" :key="index" title="Card">
<div v-if="item.val == 'radio'">
<div class="row" v-for="(i, index) in item.items" :key="index">
<div class="col-1">
<n-icon size="25">
<radio-icon></radio-icon>
</n-icon>
</div>
<div class="col-10">
<n-input
:ref="el => {if (el) inputs[index] = el}"
@focus="$event.target.select()"
v-model:value="i.name"
placeholder="taper ici"
>
</n-input>
</div>
<div class="col-1">
<n-button v-if="item.items.length > 1"
@click="deleteOption(item.id, i.id)"
>
<n-icon size="20">
<delete-icon />
</n-icon>
</n-button>
</div>
</div>
</div>
</n-card>
script:
const Add = id => {
const found = counter.value.find(item => item.id === id)
if (found.items.length > 0){
let lastValue = found.items[found.items.length-1].inc
lastValue++
found.items.push(
{
id: new Date().valueOf(),
name: `option ${lastValue}`,
inc: lastValue
}
)
inputs.value[inputs.value.length-1].focus()
console.log(inputs.value[inputs.value.length-1])// here I get before last value
console.log(inputs.value.at(-1))// here I get before last value
console.log(inputs.value)//here I get all inputs including last one
}
else {
let lastValue = 1
found.items.push(
{
id: new Date().valueOf(),
name: `option ${lastValue}`,
inc: lastValue
}
)
}
}
pls guys help and sorry for my bad English. I'll push the code in github. if anyone wanna see the full code and wants to help. I'll appreciate any help. Its driving me crazy.
I think the problem is, that there is no "re-render" between setting the data and trying to search it in the "ui"(inputs) list. Try to add await nextTick()
after your found.items.push
. Then vue can re-render and the v-for
will add the item to inputs
.