-
Notifications
You must be signed in to change notification settings - Fork 5k
Description
There's an example in the latest beta documentation showing how to use template refs with the composition API and v-for:
<template>
<div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
{{ item }}
</div>
</template>
<script>
import { ref, reactive, onBeforeUpdate } from 'vue'
export default {
setup() {
const list = reactive([1, 2, 3])
const divs = ref([])
// make sure to reset the refs before each update
onBeforeUpdate(() => {
divs.value = []
})
return {
list,
divs
}
}
}
</script>
During the initial mount the divs array will be populated correctly. However, there's a problem with updating if nodes are removed. Currently the example resets the array in onBeforeUpdate but that isn't quite enough to get it to work.
I've created a JSFiddle to try to demonstrate the problem using RC 5. I've followed the documentation example as closely as I could:
https://jsfiddle.net/skirtle/8ak71rne/28/
When one of the nodes is unmounted the template ref function still gets called, with an el of null. The result is that the divs array ends up with an extra null entry at the end that shouldn't be there.
I wasn't able to track down any documentation that explains what the expected behaviour of a function :ref is supposed to be. It was not immediately obvious to me that it would be passed null during unmounting. Assuming that isn't a bug it should probably be documented somewhere.
For the composition API example it's a small tweak to filter out the null values:
<div v-for="(item, i) in list" :ref="el => { if (el) divs[i] = el }">