在 Svelte 中导入另一个文件时保持文件的显示内容
Maintain the displayed content of a file when imported another file in Svelte
我正在学习 svelte 并且正在做一些实验,但我不知道该怎么做:当我导入文件并显示它时,我将它保存在 <pre>
标签,但是,如果我想稍后更新另一个文件,显然,它会覆盖所有内容。有代码:
<script>
let files;
</script>
<input type='file' multiple bind:files accept=".txt">
{#if files}
<h2>Files selected: </h2>
{#each Array.from(files) as file}
<p>The imported file is: {file.name}</p>
{#await file.text() then text}
<pre>{text}</pre>
{/await}
{/each}
{/if}
这是示例文件:
文件 1
I'm an example file!
文件 2
I'm another example file!
文件 3:
And i was imported after
所以我导入了 File1 和 File2,但是如果我在它们之后导入 File3,它会给我这个:
And i was imported afer
如何将最新的文件添加到其他文件中?
提前致谢。
有两种方法可以解决这个问题:
1) 不使用绑定
第一种方法是停止使用bind:files
并在用户添加文件时自行管理文件数组。
<script>
let files = [];
function handleChange(ev) {
files = [...ev.target.files, ...files]
}
</script>
<input type='file' multiple on:change={handleChange} accept=".txt">
<!-- markup goes here -->
{#each files as file}
...
{/each}
2) 使用绑定和第二个数组
使用此方法您仍然可以使用 bind:files
语法,但您实际上并没有使用 files 变量,而是将此数组的内容复制到一个然后使用的第二个数组:
<script>
let files = []
let _files = []
$: _files = [...files, ..._files]
</script>
<!-- markup goes here, but use _files instead -->
{#each _files as file}
...
{/each}
作为奖励,这两种情况都不再需要 Array.from
,因为传播语法可以做到这一点!但是,现在您必须在 if 中检查数组的长度,因为现在 files
(或 _files
)始终存在。
但是您可能有兴趣知道您可以这样做:
{#each array as item}
something with item
{:else}
array is empty
{/each}
所以您不再需要 #if
。
我正在学习 svelte 并且正在做一些实验,但我不知道该怎么做:当我导入文件并显示它时,我将它保存在 <pre>
标签,但是,如果我想稍后更新另一个文件,显然,它会覆盖所有内容。有代码:
<script>
let files;
</script>
<input type='file' multiple bind:files accept=".txt">
{#if files}
<h2>Files selected: </h2>
{#each Array.from(files) as file}
<p>The imported file is: {file.name}</p>
{#await file.text() then text}
<pre>{text}</pre>
{/await}
{/each}
{/if}
这是示例文件: 文件 1
I'm an example file!
文件 2
I'm another example file!
文件 3:
And i was imported after
所以我导入了 File1 和 File2,但是如果我在它们之后导入 File3,它会给我这个:
And i was imported afer
如何将最新的文件添加到其他文件中? 提前致谢。
有两种方法可以解决这个问题:
1) 不使用绑定
第一种方法是停止使用bind:files
并在用户添加文件时自行管理文件数组。
<script>
let files = [];
function handleChange(ev) {
files = [...ev.target.files, ...files]
}
</script>
<input type='file' multiple on:change={handleChange} accept=".txt">
<!-- markup goes here -->
{#each files as file}
...
{/each}
2) 使用绑定和第二个数组
使用此方法您仍然可以使用 bind:files
语法,但您实际上并没有使用 files 变量,而是将此数组的内容复制到一个然后使用的第二个数组:
<script>
let files = []
let _files = []
$: _files = [...files, ..._files]
</script>
<!-- markup goes here, but use _files instead -->
{#each _files as file}
...
{/each}
作为奖励,这两种情况都不再需要 Array.from
,因为传播语法可以做到这一点!但是,现在您必须在 if 中检查数组的长度,因为现在 files
(或 _files
)始终存在。
但是您可能有兴趣知道您可以这样做:
{#each array as item}
something with item
{:else}
array is empty
{/each}
所以您不再需要 #if
。