{

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.

You can check my previous posts

Vuejs Unique Identifier introduction

Unique Identifier Generation is needed in any application of every language.

This can be used in the Database as primary keys like id in MongoDB in backend applications or you can store session-id in front-end MVC applications like Angular or vueJS.

UUID or GUID is an alias that both refer same and contains 16 bytes or 128 bits in size separated into 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 the npm package

We can generate GUID in multiple ways,

vue-uuid usage example

vue-uuid is an npm package for nodejs Applications.

First, you need to install it using the 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 a global module defined in a vue-uuid library.

Before using this global object and properties, You need to import them into your mail.js file. T

his 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.use(UUID);  
  
Vue.config.productionTip = false  
  
new Vue({  
  render: h => h(App)  
}).$mount('#app')  

Once globally configured, the uuid object is available inside the template of your Vue components.

Vue Component for UUID generation In the script tag of the Vue component, First import the UUID object and call uuid.v1() returns GUID or UUID

<template>  
  <div id="app">  
    <h1 class="uuid">{{ uuid }}</h1>  
  </div>  
</template>  
  
<script>  
  import { uuid } from 'vue-uuid' // Import uuid  
  export default {  
   data () {  
      return {  
        uuid: uuid.v1(),  
      
      }  
    }  
  }  
</script>  
  
<style>  
#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;  
}  
</style>  

Output is

1f5cdb80-cd7f-11e8-bf21-1dd90afe8dad  

Custom UUID code to generate a unique id

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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.