重新创建一个组件? [英] Recreate a component?

查看:37
本文介绍了重新创建一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 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).

推荐答案

,使用 {#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

这篇关于重新创建一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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