Search code examples
uuidvuejs3

Vue 3 and Installing UUID demo


I'm new Vue 3 and finding the examples which are often written for Vue 2 to be incompatible with Vue 3. In this question, I can't find any information about the compatibility of UUID on the documentations github site. But assuming the version that installed with Vue 3 is the correct version.

After installing Vue 3 using npm, I created a new project by running "vue create myProject". The Hello World page displayed correctly. Then installed uuid again using "npm i vue-uuid" which was successful.

I added the code as described on the github page for uuid. Got errors about "use" was unknown so modified the main.js code as shown below. Now I get an error that reads "Uncaught TypeError: Cannot set property '$uuid' of undefined".

I'm lost and wondering why it has to be so hard? Any help would be appreciated.

main.js

import { createApp } from 'vue'
import App from './App.vue'

//import Vue from "vue";
import UUID from "vue-uuid"

//Vue.use(UUID);

createApp(App).use(UUID).mount('#app')

App.Vue

<template>
  <div class="uuid-panel">
    <h3 class="uuid">{{ uuid }}</h3>
    <button class="button" @click="uuid = $uuid.v1()">Generate V1</button>
    <button class="button" @click="uuid = $uuid.v3()">Generate V3</button>
    <button class="button" @click="uuid = $uuid.v4()">Generate V4</button>
    <button class="button" @click="uuid = $uuid.v5('Name 1', NAMESPACE)" >Generate V5</button>
  </div>
</template>

<script>
 import { uuid } from 'vue-uuid' 
 const NAMESPACE = "65f9af5d-f23f-4065-ac85-da725569fdcd"
export default {
  name: 'App',
  data () {
      return {
        NAMESPACE,
        uuid: uuid.v1(),
        v1: this.$uuid.v1(),
        v3: this.$uuid.v3(),
        v4: this.$uuid.v4(),
        v5: this.$uuid.v5("Name 2", NAMESPACE)
      };
    }
}
</script>

And package.json

 "name": "myProject",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-uuid": "^2.0.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0"
  }
}

Solution

  • You can use uuid

    npm install uuid
    

    then in the script part:

    import { v4 as uuidv4 } from "uuid";
    

    That's it! Calling uuidv4() will give you, your desired random UUID.