How to useVue’s _uid in Vue

In this approach, we are using the _uid property which is used to automatically assign to each component instance. This is like a unique identifier. By accessing the value of this._id in the mounted hook of the component, we can set the unique ID for each instance.

Syntax:

mounted() {
this.uniqueId = this._uid;
}

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Example 1</title>
    <script src=
"https://cdn.jsdelivr.net/npm/vue@2"></script>
    <style>
        #app {
            text-align: center;
            margin-top: 20px;
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <div id="app">
        <h1>w3wiki</h1>
        <h3>Approach 1: Using Vue's _uid</h3>
        <button @click="compAdd">Add Component</button>
        <div v-for="component in components"
             :key="component.id">
            <my-comp></my-comp>
        </div>
    </div>
    <script type="text/x-template" id="my-comp-template">
        <div>
          Component with ID: {{ uniqueId }}
        </div>
      </script>
    <script>
        Vue.component('my-comp', {
            template: '#my-comp-template',
            data() {
                return {
                    uniqueId: null,
                };
            },
            mounted() {
                this.uniqueId = this._uid;
            },
        });
        new Vue({
            el: '#app',
            data: {
                components: [],
            },
            methods: {
                compAdd() {
                    this.components.push({});
                }
            }
        });
    </script>
</body>
 
</html>


Output:

How to Set a Unique ID for Each Component Instance in VueJS ?

In Vue.js we can assign the unique ID to each of the component instances for properly managing the components in the application. In this article, we will see the different approaches to setting the unique ID for each component instance in VueJS.

These are the following approaches:

Table of Content

  • Using Vue’s _uid
  • Using Global MixIn

Similar Reads

Approach 1: Using Vue’s _uid

In this approach, we are using the _uid property which is used to automatically assign to each component instance. This is like a unique identifier. By accessing the value of this._id in the mounted hook of the component, we can set the unique ID for each instance....

Approach 2: Using Global MixIn

...