Subscribe on changes!

使用v-for给对象设置ref,且ref来自vfor的数组元素时,ref.value会从原本的对象变成数组

avatar
Jun 21st 2022

Vue version

3.2.37

Link to minimal reproduction

https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCB7IHJlZiwgb25Nb3VudGVkIH0gZnJvbSAndnVlJ1xuXG5jb25zdCBhcnIgPSBbXG5cdHtcbiAgICB0OiAnMScsXG4gICAgcmVmOiByZWYoKVxuICB9LFxuICBcdHtcbiAgICB0OiAnMicsXG4gICAgcmVmOiByZWYoKVxuICB9LFxuICBcdHtcbiAgICB0OiAnMycsXG4gICAgcmVmOiByZWYoKVxuICB9XG5dXG5cbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxkaXYgdi1mb3I9XCJvIGluIGFyclwiIDpyZWY9XCJvLnJlZlwiPlxuICAgICAgaXMgYXJyYXkge3tBcnJheS5pc0FycmF5KG8ucmVmLnZhbHVlKX19ICB7e28ucmVmLnZhbHVlfX1cbiAgPC9kaXY+XG48L3RlbXBsYXRlPiIsImltcG9ydC1tYXAuanNvbiI6IntcbiAgXCJpbXBvcnRzXCI6IHtcbiAgICBcInZ1ZVwiOiBcImh0dHBzOi8vc2ZjLnZ1ZWpzLm9yZy92dWUucnVudGltZS5lc20tYnJvd3Nlci5qc1wiXG4gIH1cbn0ifQ==

Steps to reproduce

运行以下代码

<script setup>
import { ref, onMounted } from 'vue'

const arr = [
    {
    t: '1',
    ref: ref()
  },
      {
    t: '2',
    ref: ref()
  },
      {
    t: '3',
    ref: ref()
  }
]

</script>

<template>
  <div v-for="o in arr" :ref="o.ref">
      is array {{Array.isArray(o.ref.value)}}  {{o.ref.value}}
  </div>
</template>

What is expected?

arr 中每一个对象的 ref 属性应该挂载 HTMLDivElement

type RefType = typeof arr[number]['ref']['value'] // expect HTMLDivElement

What is actually happening?

arr 中每一个对象的 ref 属性应该挂载 [HTMLDivElement]

type RefType = typeof arr[number]['ref']['value'] // expect [HTMLDivElement]

System Info

System:
    OS: Windows 10 10.0.19043
    CPU: (16) x64 AMD Ryzen 9 5900HX with Radeon Graphics
    Memory: 5.55 GB / 15.40 GB
  Binaries:
    Node: 16.11.1 - C:\Program Files\nodejs\node.EXE
    npm: 8.0.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.1266.0), Chromium (102.0.1245.44)
    Internet Explorer: 11.0.19041.1566
  npmPackages:
    vue: ^3.2.36 => 3.2.37

Any additional comments?

No response

avatar
Jun 21st 2022

that's not how the normal v-for template ref is meant to be used. For your use case, use a function.

  <div v-for="o in arr" :ref="(e) => o.ref.value = e">