gpt4 book ai didi

svelte - 上下文 ="module"如何在 Svelte 和 Sapper 中工作?

转载 作者:行者123 更新时间:2023-12-03 19:42:13 28 4
gpt4 key购买 nike

当我在从服务器获取数据时使用 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>

最佳答案

考虑一个导出类的常规 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> 中发生的情况。标签
  • 关于svelte - 上下文 ="module"如何在 Svelte 和 Sapper 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62185374/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com