A tiny, SSR-safe directive for binding random data to an element.
A tiny, SSR-safe directive for binding random data to an element.
First install vue-bind-once
:
yarn add vue-bind-once
# or npm
npm install vue-bind-once --save
import { createApp } from 'vue'
import { BindOnceDirective, BindOncePlugin } from 'vue-bind-once'
import App from './App.vue'
const app = createApp(App)
app.use(BindOncePlugin)
// or app.directive('bind-once', BindOnceDirective)
In most cases you'll be using this directive with an SSR-rendering framework like nuxt
, which may have a different way for you to register this directive. For example, in a Nuxt plugin:
import { BindOncePlugin } from 'vue-bind-once'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(BindOncePlugin)
})
You can now use the directive on any element where you need a binding to a value that needs to match between client/server but won't change dynamically afterwards.
<script setup>
import { nanoid } from 'nanoid'
const id = nanoid()
</script>
<template>
<input type="text" v-bind-once="{ id, name: id }" />
<label v-bind-once="{ for: id }" />
</template>
This will work on both server and on client re-hydration.
This has been developed to suit my needs but additional use cases and contributions are very welcome.
MIT License - Copyright © Daniel Roe