'How to generate UID that will persist in both server and client side in nuxt?
Maybe the heading is misleading, so I described my issue as thoroughly as I could.
I have a class that generates some id for itself.
class Div {
id = null
constructor() {
// some more data
this.id = id()
}
onMounted() {
const HTMLElement = document.getElementById(this.id)
HTMLElement.style.setProperty('--custom-property', 'lol')
// do some stuff
}
}
Then I render it on server-side (sorry for Pug):
<template lang="pug">
.divs
div(
v-for="div in divs"
:id="div.id"
) {{ div.data }}
</template>
After in onMounted hook I want to apply some dynamic generated stuff like styles or custom properties (as you can see above):
setup() {
const divs = [
new Div(),
new Div(),
new Div()
]
onMounted(() => {
divs.forEach(div => div.onMounted())
})
return {
divs
}
}
The problem is that the actual id's in array and in the DOM are different, so I got undefined while tring to call getElementById().
The reason why I am doing this is that I am creating a plugin and need these blocks to be rendered on server-side (by obvious reasons), but I need to set some custom properties because they will be provided by the end user. I don't think there is an other way to solve this, but I am open to any suggestions. Maybe it's a common issue that is solved already?
I also have no idea why id's are different, because I though that classes instantiated once on server, but it seems like they do it twice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
