当我使用 Sapper 构建项目时,每当我从服务器获取数据时,预加载函数都会在 script 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 https://svelte.dev/docs
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>
考虑一个导出类的常规 JavaScript 模块:
// Component.js
console.log('evaluating module');
export class Component {
constructor() {
console.log('instantiating component');
}
}
如果您将该模块导入到您的应用程序中,该代码将立即运行:
import { Component } from './Component.js';
// "evaluating module" has already been logged. This will only happen once
// for the entire application, however many modules import Component.js
const component1 = new Component(); // logs "instantiating component"
const component2 = new Component(); // logs "instantiating component" again
现在我们可以用 Svelte 的术语来表述:
- “评估模块”代码发生在
<script context="module">
- “实例化组件”代码与常规中发生的情况等效
<script>
tag
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)