【发布时间】:2020-09-22 21:23:35
【问题描述】:
当我从服务器获取数据时使用 Sapper 构建项目时,预加载函数在脚本 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>
根据document
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>
【问题讨论】:
-
AFAIK,不像
onMount每个组件实例调用一次,context="module"脚本只执行一次。