有没有办法在打字文件中使用svelte、getContext等svelte函数? [英] Is there a way to use svelte getContext etc. svelte functions in Typescript files?

查看:7
本文介绍了有没有办法在打字文件中使用svelte、getContext等svelte函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为项目中的情态程序使用svelte-simple-modal的getContext。

有没有办法在TypeScrip文件中使用getContext等? 在文字脚本文件中调用svelte函数时出现500: Function called outside component initialization

我已经尝试了how-do-you-import-a-svelte-component-in-a-typescript-file中提到的方法。

谢谢您的帮助!

推荐答案

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

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

您不能在组件初始化之外调用getContextsetContext或Svelte的任何生命周期函数,这意味着您不能调用它

  • 异步(例如在超时后)
  • 响应组件的DOM事件
  • ETC

这篇关于有没有办法在打字文件中使用svelte、getContext等svelte函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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