Open In App

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

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

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=
    <style>
        #app {
            text-align: center;
            margin-top: 20px;
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <div id="app">
        <h1>GeeksforGeeks</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:

Output1

Approach 2: Using Global MixIn

In this approach, we are using the global mixin to generate unqiueIDs with custom prefixes and length. We have applied the mixin globally to all the components and each time when the Add Component button is clicked, a new instance of the component is created with the unique ID generated by the idFn method.

Syntax:

// global mixin
const myGlobalMixin = {
data() {
return {
// properties
};
},
methods: {
// methods
},
};
// use the global mixin
Vue.mixin(myGlobalMixin);

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

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Example 2</title>
    <script src=
      </script>
</head>
 
<body>
    <div id="app">
        <h1 style="color: green;">
              GeeksforGeeks
          </h1>
        <h3 style="color: black;">
              Approach 2: Using Global MixIn
          </h3>
        <div>
            <label for="pre">ID Prefix:</label>
            <input type="text" id="pre"
                   v-model="pre" placeholder="Enter a prefix">
        </div>
        <div>
            <label for="length">Length:</label>
            <input type="number" id="length"
                   v-model.number="idLen" min="1" max="10">
        </div>
        <button @click="compAdd">Add Component</button>
        <div v-for="(component, index) in components" :key="index">
            <unique-id-component :instance-id="component.instanceId">
 
            </unique-id-component>
        </div>
        <script>
            Vue.mixin({
                data() {
                    return {
                        componentCount: 0,
                    };
                },
                methods: {
                    idFn() {
                        const randomPart = Math.random()
                            .toString(36).substr(2, this.idLen);
                        return `${this.pre}_${randomPart}
                                        _${this.componentCount++}`;
                    },
                },
            });
            Vue.component('unique-id-component', {
                props: ['instanceId'],
                template: '<div>{{ instanceId }}</div>',
            });
            new Vue({
                el: '#app',
                data: {
                    pre: 'demo',
                    idLen: 4,
                    components: [],
                },
                methods: {
                    compAdd() {
                        this.components.push({
                            instanceId:
                                this.idFn()
                        });
                    },
                },
            });
        </script>
    </div>
 
</body>
 
</html>


Output:

Output2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads