Vuejs - Generate Unique Identifier - UUID or GUID with example

In this blog post, We are going to learn how to generate UUID or GUID in the vuejs application with examples.
In my previous post, We already learned about a guide to GUID, UUID, DUID in javascript.

Vuejs Unique Identifier introduction

Unique Identifier Generation is required in any application of every language. This can be used in Database primary keys or you can store session id in front-end MVC applications like Angular or vueJS.
UUID or GUID is alias both refers same and contains 16 bytes or 128 bits in size separated in 5 groups by hyphens.

There are different ways to create a UUID in vuejs applications

  • Using existing npm packages like vue-uuid
  • Custom UUID code to generate a unique id

Example for Generating Unique Identifier using npm package

vue-uuid usage example

vue-uuid  is an npm package for Vuejs Applications. First, you need to install it using npm install command

npm install --save vue-uuid  

This generates dependency in node_modules and adds an entry in the dependency section of package.json
Import UUID module in the application
UUID is global module defined in vue-uuid. Before using this global object and properties, You need to import in your mail.js file. This vue-uuid is globally available by calling Vue.use with uuid main.js

import Vue from 'vue'  
import App from './App.vue'  
import UUID from 'vue-uuid'  
Vue.config.productionTip = false  
new Vue({  
  render: h => h(App)  

Once globally configured, uuid object is available inside the template of your vue components.
Vue Component for UUID generation
In the script tag of vue component, First import uuid object and calling uuid.v1() returns GUID or UUID

  <div id="app">  
    <h1 class="uuid">{{ uuid }}</h1>  
  import { uuid } from 'vue-uuid' // Import uuid  
  export default {  
   data () {  
      return {  
        uuid: uuid.v1(),  
#app {  
  font-family: 'Avenir', Helvetica, Arial, sans-serif;  
  -webkit-font-smoothing: antialiased;  
  -moz-osx-font-smoothing: grayscale;  
  text-align: center;  
  color: #2c3e50;  
  margin-top: 60px;  

Output is


Custom UUID code to generate a unique id

You can copy the javascript function UUID generation code and create a method in vue component. display it in template

Similar Posts