Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Composition API template refs with v-for example - update problem #353

Closed
skirtles-code opened this issue Jul 29, 2020 · 1 comment
Closed

Comments

@skirtles-code
Copy link
Contributor

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>

Source Link

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 }">
@NataliaTepluhina
Copy link
Member

Thank you! I've fixed the code snippet with b9217d8 for now and will take a deeper look on what is passed on unmounting. Maybe it'd be better to fix on the source code rather than on docs 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants