This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can vue provide useId
hook
#556
Comments
I've released a tiny directive that may help: vue-bind-once. Sample usage: <div v-bind-once="{ id: Math.random() }" /> This will work on both server and on client re-hydration. |
@danielroe Is this method only available for binding on elements? I want this id to be available everywhere,like hooks. |
Another option (not as flexible as vue-bind-once but inspired by it) is: vue-uid It generates an SSR-friendly unique identifier that is automatically assigned to the Sample usage: <script setup lang="ts">
import { ref } from 'vue'
const input = ref<null | HTMLElement>(null)
</script>
<template>
<div>
<label :for="input?.id">Input label</label>
<input v-uid ref="input" type="text">
</div>
</template> Both |
In case you’re looking for a composable, I came up with that solution: https://github.com/liip/chusho/blob/main/packages/chusho/lib/composables/useCachedUid.ts#L20-L41 |
is there any idea for vue2? |
@LeBenLeBen I see different values for client and server when I use that composable in Nuxt |
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
What problem does this feature solve?
In the SSR environment, sometimes it is necessary to create a stable id that is the same on the server and the client.
For example, a server request wants to put the requested data in html (for example
window.SSR_DATA={//data}
), and then the client obtains and uses the data through a specifickey
fromSSR_DATA
.We can encapsulate this method into a hook, for example called
useServerData
.useServerData
may be used multiple times by the same component, or it may be used by multiple components. Therefore, thiskey
is required to be globally unique and the same in the same place on the server and client.We can also guarantee uniqueness by passing the
key
touseServerData
. But this is very inelegant and there is no way to guarantee that it will be unique. For example,useServerData
is used in multiple components, so we need to go to each component code to confirm whether there is any duplication.In fact, thiskey
does not need to be concerned about the component at all.So can vue provide a way to generate id staying stable and unique between server and client?
A similar hook is provided in
react18
, you can refer to.What does the proposed API look like?
The text was updated successfully, but these errors were encountered: