Thursday, October 11, 2018

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.use(UUID);

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#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
<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 vue component. display it in template

Related article


EmoticonEmoticon