• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

重新创建组件?

用户头像
it1352
帮助4

问题说明

有没有办法在 Svelte 中重新创建组件?

Is there a way to recreate a component in Svelte?

上下文是我有一个已经创建的组件.一旦它完成它的过程,我希望它被销毁然后再次创建.这会将其属性恢复为默认状态,并确保对其嵌套组件执行相同操作.

The context is that I have a component which has already been created. Once it completes its process, I would like for it to be destroyed and then created again. This would restore its properties to their default state, and ensure that the same is done for its nested components.

我认为使用现有的组件方法在技术上是可行的,但我想知道是否有一种直接的方法来实现它.

I imagine that this is technically possible with the existing component methods, but I was wondering if there's a straightforward way to go about it.

顺便说一句,我知道在某些情况下重新创建组件可能效率低下.通过手动重置组件及其嵌套组件的状态来实现所需的娱乐效果可能更可取.例如,递归函数可以以某种方式遍历组件及其嵌套组件,并调用每个组件的默认数据函数.然而,这并不是那么简单,而且存在问题(即计算属性和创建生命周期挂钩).

As an aside, I'm aware that recreating a component might be inefficient in some contexts. It might be preferable to achieve the desired recreation effect by manually resetting the state of the component and its nested components. For instance, a recursive function could somehow traverse the component and its nested components, and invoke the default data function of each. However, this is not so straightforward, and there are problematic aspects (i.e. computed properties and creation lifecycle hooks).

正确答案

#1

,使用 {#key} 块:

<script>
import YourComponent from "./YourComponent.svelte"

let unique = {}

function restart() {
  unique = {} // every {} is unique, {} === {} evaluates to false
}
</script>

{#key unique}
  <YourComponent />
{/key}

<button on:click={restart}>Restart</button>

REPL

{#key} 是在 Svelte v3.28 中引入的,在此之前您需要使用键控 {#each}只有一项

{#key} was introduced in Svelte v3.28, before that you needed to use a keyed {#each} block with only one item

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfigkg
系列文章
更多 icon
同类精品
更多 icon
继续加载