I have several similar elements that are defined as follows:
<script setup>
const el1 = ref()
const el2 = ref()
const el3 = ref()
</script>
<template>
<h1 ref="el1"></h1>
<h1 ref="el2"></h1>
<h1 ref="el3"></h1>
</template>
I want to combine all of ref
elements into a new reactive variable and use their attributes.
What is the best approach for handling this?
3
Answers
For looping over multiple items, use refs inside v-for.
For joining multiple separate
refs
, use reactive():<script>
<script setup>
You have 2 options:
state.el1
,state.el2
in<template />
)toRefs
) – Con: you have to specify each ref when extracting:The bigger advantage of using
reactive
is that you no longer need to use.value
inside thescript
(Usestate.el1
in both<script>
and<template>
.Try the following and let me know if that’s what you were trying to achieve 🙂
edit: if you want to loop dynamically, try the following
Shown in the example below two cases, in
v-for
and through a function:ref
(if you need to combine elements without a loop):Vue SFC Playground
Docs:
Refs inside v-for
andFunction Refs
.