在Svelte和Sapper中,CONTEXT="模块"是如何工作的? [英] How context="module" works in Svelte and Sapper?

查看:0
本文介绍了在Svelte和Sapper中,CONTEXT="模块"是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我从服务器获取数据时,当我使用Sapper构建项目时,预加载函数在脚本上下文="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>

推荐答案

考虑一个导出类的常规Java模块:

// 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

现在我们可以用简略的术语来表示:

  • <script context="module">
  • 中发生的情况就是‘评估模块’代码
  • "实例化组件"代码等同于在常规<script>标记中发生的操作

这篇关于在Svelte和Sapper中,CONTEXT=&QUOT;模块&QUOT;是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆