是否有一种简便的方法可以强制重新启动Svelte组件?
重新启动用例:
除了重新启动之外,也许还有其他解决方案,但是让我们在这里使用组件重新启动。
下面的重新启动代码对上载用例非常有效:
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}/>
Upload.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
}
答案 0 :(得分: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>
{#key}
在Svelte v3.28中引入,在此之前,您需要使用键控{#each}
块with only one item