Categories
Vue Answers

How to Set a Unique ID for Each Component Instance?

Spread the love

Sometimes, we want to set a unique ID for each component instance in Vue.js.

In this article, we’ll look at how to set a unique ID for each component instance in Vue.js.

Set a Unique ID for Each Component Instance

We can set a unique ID for each component instance with the uuid library.

To install it, we run npm i uuid .

Then we set the UUID as the ID of the element by writing:

<template>
  <div id="app">
    <div>
      <label :for="id">Label text for {{ id }}</label>
      <input :id="id" type="text" />
    </div>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
export default {
  name: "App",
  data() {
    return {
      id: null,
    };
  },
  mounted() {
    this.id = uuidv4();
  },
};
</script>

We create the unique ID with the uuidv4 function.

And we pass that in as the value for the for and id props.

Now the input has its own unique ID.

Conclusion

We can set a unique ID for each component instance with the uuid library.

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 *