我已经创建了一个简单的组件,我在数据抓取时使用,我想在等待周期运行时也禁用按钮,我可以在模板中使用{disabled = true}
和{disabled = false}
,但这会呈现这些值,还有其他方法可以做到这一点吗?
<script>
import Fa from "@node_modules/svelte-fa/src/fa.svelte"
import { faSpinner } from "@fortawesome/free-solid-svg-icons"
export let text = ""
export let promise
let className
let disabled = false
export {className as class}
</script>
<button
class={className} disabled={disabled}
>
{#await promise}
<Fa icon={faSpinner} class="rotate" />
{:then}
{ text }
{/await}
</button>
我稍微简化了一下你的例子,但是试试这样做:
<!-- Loader.svelte -->
<script>
export let promise;
let disabled = true;
// when promise changes, disable the button again
$: {
disabled = true;
promise.then(() => {
disabled = false;
});
}
</script>
<button {disabled}>
{#await promise }
Loading...
{:then}
Loaded
{/await}
</button>
下面是该组件的演示。
<!-- App.svelte -->
<script>
import Loader from './Loader.svelte';
let promise;
initPromise();
function initPromise() {
promise = new Promise(resolve => setTimeout(resolve, 1000));
}
</script>
<Loader {promise} />
<button on:click={initPromise}>
Reset promise
</button>