Bootstrap

vueuse中的useTemplateRefsList

在 v-for 中绑定 ref 到模板元素和组件的简写方式

Demo1

<script setup lang="ts">
import { onUpdated } from 'vue'
import { useTemplateRefsList } from '@vueuse/core'

const refs = useTemplateRefsList<HTMLDivElement>()

onUpdated(() => {
  console.log(refs)
})
</script>

<template>
  <div v-for="i of 5" :key="i" :ref="refs.set" />
</template>

Demo2

<script setup lang="ts">
import { useTemplateRefsList } from '@vueuse/core'
import { nextTick, ref, watch } from 'vue'

const count = ref(5)
const refs = useTemplateRefsList<HTMLDivElement>()

watch(refs, async () => {
  await nextTick()
  console.log([...refs.value])
}, {
  deep: true,
  flush: 'post',
})
</script>

<template>
  <span v-for="i of count" :key="i" :ref="refs.set" class="mr-2">
    {{ i }}
  </span>
  <br>
  <button @click="count += 1">
    Inc
  </button>
  <button :disabled="count <= 0" @click="count -= 1">
    Dec
  </button>
  <note>Open the console to see the output</note>
</template>
;