每当我从服务器获取数据时,我都使用 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>
Run Code Online (Sandbox Code Playgroud)
根据文件
A <script> tag with a context="module" attribute runs once when the module first evaluates, rather than for each component instance.
Run Code Online (Sandbox Code Playgroud)
但是当模块第一次评估时是什么意思?
这是否意味着组件首次呈现时?那么和下面的代码一样在 onMount 生命周期方法中声明 api fetch 函数不一样吗?
<script>
onMount(async() => {
const res = await fetch(`https://reqres.in/api/users?page=1`);
const json = await res.json();
})
</script>
Run Code Online (Sandbox Code Playgroud)
Ric*_*ris 13
考虑一个导出类的常规 JavaScript 模块:
// Component.js
console.log('evaluating module');
export class Component {
constructor() {
console.log('instantiating component');
}
}
Run Code Online (Sandbox Code Playgroud)
如果您将该模块导入您的应用程序,该代码将立即运行:
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
Run Code Online (Sandbox Code Playgroud)
现在我们可以用 Svelte 术语来表达:
<script context="module"><script>标签中发生的事情| 归档时间: |
|
| 查看次数: |
2397 次 |
| 最近记录: |