有没有办法在 Typescript 文件中使用 svelte getContext 等 svelte 函数?

2024-02-01

我正在使用 getContext 与苗条简单模态 https://www.npmjs.com/package/svelte-simple-modal对于我的项目中的模态。

有没有办法在 Typescript 文件中使用 getContext 等? 我得到了500: Function called outside component initialization在 Typescript 文件中调用 svelte 函数时。

我已经尝试过中提到的方法如何在打字稿文件中导入精简组件 https://stackoverflow.com/questions/62761623/how-do-you-import-a-svelte-component-in-a-typescript-file.

谢谢你的帮助!


您可以使用getContext在 TypeScript 文件内,但您只能在组件初始化期间调用它 - 即第一次运行组件脚本标记的内容。

// TS code
import { getContext } from 'svelte';

export function getFooContext() {
  const foo = getContext('foo');
}

export function fails() {
  setTimeout(() => getFooContext(), 100);
}

// Svelte code
<script>
  import { getFooContext } from './somewhere';
  
  // this is ok
  getFooContext();
  // this fails because it's called after the component is initialized
  setTimeout(() => getFooContext(), 100);
  // this fails because the function has a setTimout which is resolved
  // after the component is initialized
  fails();
</script>

你不能打电话getContext or setContext或组件初始化之外的任何 Svelte 生命周期函数,这意味着您无法调用它

  • 异步(例如超时后)
  • 响应组件的 DOM 事件
  • etc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法在 Typescript 文件中使用 svelte getContext 等 svelte 函数? 的相关文章