我想在 SvelteKit 中制作一个具有随机参数的组件。问题在于,当页面在服务器端呈现时与页面变为水合时,此参数所取的值是不同的。
例如,考虑这个组件:
<script>
export let t = Math.random() * 90
export let l = Math.random() * 90
</script>
<div class="box" style="--t: {t}vh; --l: {l}vw;"></div>
<style>
.box {
position: fixed;
top: var(--t); left: var(--l);
width: 10vw; height: 10vh;
background-color: black;
transition: all 1s;
}
</style>
当页面在服务器上渲染时,t
和 l
取一些随机值,结果以 HTML 格式返回给浏览器。然而,一旦页面变得湿润,t
和 l
采取不同的值(value)观。结果,盒子移动了。我不想让盒子移动;而是,我希望服务器返回的随机值也被客户端使用所以没有一闪而过的风格变化。如果页面通过页内路由器导航,一切都很好;当页面被服务器渲染时,框移动。
如果我导出
load
,结果是一样的功能。 SvelteKit 有没有办法让服务器和客户端就随机值达成一致?
最佳答案
你有几个选择:
<script>
import { onMount } from 'svelte';
let t, l;
onMount(() => {
t = Math.random() * 90;
l = Math.random() * 90;
})
</script>
{#if t && l }
<div class="box" style="--t: {t}vh; --l: {l}vw;"></div>
{/if}
<style>
.box {
position: fixed;
top: var(--t); left: var(--l);
width: 10vw; height: 10vh;
background-color: black;
transition: all 1s;
}
</style>
// random.json.js
export async function get() {
return {
body: {
t: Math.random() * 90,
l: Math.random() * 90,
},
};
}
<!-- index.svelte -->
<script context="module">
export async function load({ fetch }) {
// this will be cached, so it will be the same on client & server
const result = await fetch('/random.json');
const { t, l } = await result.json();
return {
props: {
t, l
}
}
}
</script>
<script>
export let t;
export let l;
</script>
<div class="box" style="--t: {t}vh; --l: {l}vw;"></div>
<style>
.box {
position: fixed;
top: var(--t); left: var(--l);
width: 10vw; height: 10vh;
background-color: black;
transition: all 1s;
}
</style>
就个人而言,我更喜欢第二种选择,因为没有 FOUC。
关于javascript - SvelteKit 渲染随机 Prop 在服务器和客户端之间是不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70714461/