@shimyshack/uid

An SSR-friendly Vue directive that generates a unique ID for elements.
19,260 25
Install
npm install @shimyshack/uid
Latest Version:0.1.9
Vue:3
License:MIT
Last Updated:Jun 16, 2023
Links: GitHub  ·  npm
Maintainer: jshimkoski

vue-uid

An SSR-friendly Vue directive that generates a unique ID for elements.

Quick Start

Install @shimyshack/uid:

npm install @shimyshack/uid --save

# or yarn
# yarn add @shimyshack/uid

Register Directive

import { createApp } from 'vue'
import App from './App.vue'
import { Uid, UidPlugin } from '@shimyshack/uid'

createApp(App)
  .use(UidPlugin)
  // or .directive('uid', Uid)
  .mount('#app')

In Nuxt, create a plugin to take advantage of SSR-support:

import { UidPlugin } from '@shimyshack/uid'

export default defineNuxtPlugin(({ vueApp }) => {
  vueApp.use(UidPlugin)
})

Usage

You can now use the directive on any element in which you need to register a unique id.

Single Element

<script setup lang="ts">
import { ref } from 'vue'
const input = ref<HTMLElement>()
</script>

<template>
  <div>
    <label :for="input?.id">Input label</label>
    <input v-uid ref="input" type="text">
  </div>
</template>

Array of Elements

<script setup lang="ts">
import { ref } from 'vue'
const formInputRefs = ref<HTMLElement[]>([])
const form_fields = [
  { label: 'Field 1', name: 'field_1' },
  { label: 'Field 2', name: 'field_2' },
]
</script>

<template>
  <div v-for="(field, index) in form_fields">
    <label :for="formInputRefs[index]?.id">
      {{ field.label }}
    </label>
    <input v-uid ref="formInputRefs" :name="field.name" />
  </div>
</template>

This will work on both server and client re-hydration.

Contributors

This was inspired by the work of Daniel Roe on vue-bind-once, but simplified to fit my needs.

For more advanced use cases, I suggest you check out his work.

License

MIT License - Copyright © Jason Shimkoski

Related Packages

vue-bind-once

A tiny, SSR-safe directive for binding random data to an element.

152,016 169
vue-frag

Vue 2 fragment directive to return multiple root elements

971,885 224
vue3-highlight-text

a vue3 directive of highlight text

84,789
vue-proportion-directive

vue 固定元素比例指令

6,003 10
ardirectives

Ardirectives

811

Version History

Version Released License
0.1.9 MIT
0.1.7 MIT
0.1.6 MIT
0.1.5 MIT
0.1.4 MIT