当我使用Sapper构建项目时,无论何时从服务器获取数据,preload函数都声明在context="module"的脚本内,如下所示。
根据文档。
<script context="module">
export async function preload(page) {
return await this.fetch(`https://reqres.in/api/users?page=1`)
.then(res1 => {
return res1.json()
}).then(res2 => {
return {
notices: res2.data,
}
})
}
</script>
根据文档。
A <script> tag with a context="module" attribute runs once when the module first evaluates, rather than for each component instance.
但是“当模块首次评估”是什么意思?
它是否意味着当组件首次渲染时?那么在onMount生命周期方法中声明api fetch函数不就像下面的代码一样吗?
<script>
onMount(async() => {
const res = await fetch(`https://reqres.in/api/users?page=1`);
const json = await res.json();
})
</script>
onMount
不同,context="module"
的脚本仅执行一次。 - TurboHz