vuejs / vuejs/core

v-for with ref not working as suggested in documentation in some scenarios

Open
#3,418 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

has workaround
Dominant language
TypeScript
Stars
54.4k
Forks
9.2k
Avg merge
1d 5h
Merged PRs (30d)
140

Description

Version

3.0.7

Steps to reproduce

Original Docs:

import { onBeforeUpdate, onUpdated } from 'vue'

export default {
  setup() {
    let itemRefs = []
    const setItemRef = el => {
      if (el) {
        itemRefs.push(el)
      }
    }
    onBeforeUpdate(() => {
      itemRefs = []
    })
    onUpdated(() => {
      console.log(itemRefs)
    })
    return {
      setItemRef
    }
  }
}
What is expected?

Filled array for component lifetime

What is actually happening?

After component update array is empty, but lifetime is continue.


Temporary solution:
Tip: Only use and export.
Authors: @NataliaTepluhina

function useListRef<T>() {
  const elements = ref<T[]>([])
  const active = ref<boolean>(false)

  watch(active, (isActive) => {
    if (isActive) {
      nextTick(() => active.value = false)
    }
  })

  function addRef(el) {
    if (!active.value) {
      elements.value = []
      active.value = true
    }
    el && elements.value.push(el)
  }

  return {
    elements,
    addRef,
  }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the documented v-for ref example from the issue on Vue 3.0.7, then compare the array contents before and after a component update. Check whether the documented lifetime expectation matches the observed behavior and verify any proposed change against the provided temporary useListRef workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.