Sometimes, we want to add refs dynamically in our Vue.js app.
In this article, we’ll look at how to add refs dynamically in our Vue.js app.
Add Refs Dynamically in Vue.js
We can add refs dynamically in our Vue.js app by assigning the ref prop to a dynamic value.
For instance, we can write:
<template>
<div id="app">
<p v-for="d of dataArr" :key="d.id" :ref="`element-${d.id}`">{{ d.id }}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
dataArr: [{ id: 1 }, { id: 2 }, { id: 3 }],
};
},
mounted() {
const [el] = this.$refs["element-1"];
console.log(this.$refs);
console.log(el);
},
};
</script>
We set the ref prop of each element to `element-${d.id}` .
Then in the mounted hook, we get the this.$refs object, which is an object with the ref names as the property names and the array of elements as their values.
So we can destructure the first ref by writing:
const [el] = this.$refs["element-1"];
Conclusion
We can add refs dynamically in our Vue.js app by assigning the ref prop to a dynamic value.