svelte - context="module" 如何在 Svelte 和 Sapper 中工作?
问题描述
当我在从服务器获取数据时使用 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>
根据文件
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>
标记中发生的情况
推荐阅读
- f# - 在 F# 中,在换行符处将文本拆分为小于特定大小的块
- c# - 如何在 ListView 的调整大小窗口中出现 VerticalScrollBar?
- html - GMAIL 中的“邮件预览”显示替代文字
- git - 如何修复对远程分支的“陈旧”引用?
- sql - 当值在连续时间内不改变时合并行
- azure - 具有环回地址且无连接的 Azure VM 网卡
- typescript - 在打字稿中抽象出泛型类型参数
- javascript - 使用函数时在 Sequelize 中分组
- python - 在 Django 中检索由不同用户创建的模型对象
- python - 如何在谷歌云中部署 Flask ML 模型