Vuejs Generate Unique Identifier UUID or GUID with example

In this blog post, we will explore how to generate UUID or GUID in a Vue.js application with practical examples.

If you’re interested, you can also refer to my previous posts on this topic.

Vue.js Unique Identifier Introduction

The generation of unique identifiers is essential in any application, regardless of the programming language used.

Unique identifiers are commonly employed as primary keys in databases, such as MongoDB for backend applications. Additionally, they can be utilized to store session IDs in frontend MVC applications, like Angular or Vue.js.

UUID or GUID, often used interchangeably, both refer to a structure containing 16 bytes or 128 bits, separated into 5 groups by hyphens.

There are various methods to create a UUID in Vue.js applications:

  • Utilizing existing npm packages like vue-uuid.
  • Implementing custom UUID code to generate a unique ID.

Example for Generating Unique Identifier Using the npm Package

We can generate GUID in multiple ways, Let’s explore the usage of vue-uuid, an npm package for Node.js applications.

vue-uuid usage example

To use vue-uuid, you first need to install it using the npm install command:

npm install --save vue-uuid

This command generates a dependency in node_modules and adds an entry in the dependency section of package.json.

Import UUID Module in the Application The UUID module is globally defined in the vue-uuid library. Before using this global object and its properties, you must import them into your main.js file.

The vue-uuid becomes globally available by calling Vue.use with UUID in 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, import the UUID object and calluuid.v1()`, which returns a 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:

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

Custom UUID Code to Generate a Unique ID

Alternatively, you can copy the javascript function UUID generation and create a method in the Vue component to display it in the template.