Categories
Vue Answers

How to Add Refs Dynamically in Vue.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *