N
Nuxt6mo ago
IamSebastn

Avoiding style-mismatch

My goal is to position a component randomly inside a grid. But unfortunately I‘m always getting the style-mismatch warning:
- rendered on server: style="grid-column:12;"
- expected on client: style="grid-column: 10"
Note: this mismatch is check-only. The DOM will not be rectified in production due to performance overhead.
You should fix the source of the mismatch.
- rendered on server: style="grid-column:12;"
- expected on client: style="grid-column: 10"
Note: this mismatch is check-only. The DOM will not be rectified in production due to performance overhead.
You should fix the source of the mismatch.
I try to achieve my goal with the following code:
js
const computedStyle = computed(() => {
const letters = '0123456789ABCDEF'
let color = '#'
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)]
}
const style = `background: ${color}; grid-column: ${useRandomnumber(0, 12, 1)} / span 3`

return style
})

<template>
<div class="box" ref="item" :style="computedStyle"></div>
</template>
js
const computedStyle = computed(() => {
const letters = '0123456789ABCDEF'
let color = '#'
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)]
}
const style = `background: ${color}; grid-column: ${useRandomnumber(0, 12, 1)} / span 3`

return style
})

<template>
<div class="box" ref="item" :style="computedStyle"></div>
</template>
I thought that due the style prop is a template literal it would be the easiest to outsource the logic into a computable variable and pass it as a prob. But unfortunately this doesn‘t work.. Hope someone can tell me how to tackle this issue
3 Replies
manniL
manniL6mo ago
you have to avoid recalculating the random value on the client and on the server 🙂
manniL
manniL6mo ago
you can e.g. use usestate to transfer it over, or use vue-bind-once (or onPreHydrate in Nuxt maybe?) to set the value
GitHub
GitHub - danielroe/vue-bind-once: A tiny, SSR-safe directive for bi...
A tiny, SSR-safe directive for binding random data to an element. - danielroe/vue-bind-once
IamSebastn
IamSebastnOP6mo ago
Looks promising! Definitely taking a look at it ✌🏻
Want results from more Discord servers?
Add your server