8

有没有一种简单的方法可以强制重启 Svelte 组件?

重启用例:

  • 清除 HTML 文件输入的文件列表(不能重置路径/值)
  • 使用 CSS 悬停时选择项目后导航栏下拉折叠

也许除了重启还有其他解决方案,但让我们在这里使用组件重启。

在适用于上传用例的重启代码下方:

SomeApp.svelte

<script>
      ...
      import Upload from "./upload/Upload.svelte";

      export let uid;  // firebase uid from auth

      // restart the Upload component after the upload 
      // to clear the filename of the <input type="file" ..../>  
      // restart by making use of a dynamic (falsy) component
      let upload_component = Upload;
      let restart = false;

      $: if (restart) {
         // use a falsy to stop / destroy this component 
         upload_component = null;
         // use a timer to queue a restart after the component has stopped
         setTimeout(() => {
           console.log('Upload component restarts')
           upload_component = Upload
         }, 0);
         console.log('Upload component restart queued');
         restart = false;  
      };

      ...
</script>


<!-- dynamic upload to restart the component when finished-->
<svelte:component uid={uid} this={upload_component} bind:finished={restart}/>

上传.svelte

<script>
    import { onDestroy } from 'svelte';
    import { uploadCsv } from './upload.js'

    export let uid = null;
    export let finished;

    function uploadCsvCallback(result) {
      console.log(result);
      finished = true;
    };

    onDestroy(() => {
      console.log('Upload component destroyed');
    });
</script>

<style>
     .float-right {
          float: right;
      }
</style>

<!-- Select a CSV file to batch import a Firestore collection -->
<input
    type="file" name="files" class="float-right" accept=".csv" 
    on:change={uploadCsv(uid, uploadCsvCallback)}
/>

更新:
如果组件未渲染,组件将被销毁。因此,当您切换组件周围的 if 块时,您可以停止和重新启动组件。

示例:
1.将运行从 true 切换为 false 以销毁 Upload 组件
2.将 run 从 false 切换为 true 以重新启动 Upload 组件

{#if run}
  <Upload .....>
{/if}

您可以使用计时器来切换重启。

run = true:
function restartComponent() {
  restart = false;  // stop / destroy
  setTimeout(() => run = true, 0); // and queue a restart
}
4

1 回答 1

9

的,使用{#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}的键控块

于 2020-09-04T08:14:33.767 回答