如何将更新的值传递给我的组件

How to pass updated values to my component

我正在尝试实现防止双击和禁用按钮并在单击事件期间更改按钮的文本。

    let btnText = "Initial";
    let btnDisabled = false;

const handlClick = () => {
    if (btnDisabled) return;
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

<Button
      {btnDisabled}
      text={btnText}
        btnClass="btn btn-primary"
        on:click={handlClick}
      />

更新后的值似乎没有传递给组件

这是我的 Button 组件

<script>
  import { createEventDispatcher } from "svelte";

  const dispatch = createEventDispatcher();

  function click() {
    dispatch("click");
  }

  export let text = "Pending";
  export let shrink = false;
  export let btnClass = "";
  export let btnDisabled = false;
</script>

<button 
  disabled={btnDisabled} on:click={click} class={btnClass}>{text}</button>

<style>
  .button {
    border: 2px solid var(--theme_modal_button_border);
    border-radius: 0.5rem;
    padding-left: 25px;
    padding-right: 25px;
    font-size: smaller;

    font-weight: 700;
    background: var(--theme_modal_button_bg);
    color: var(--theme_button_color);
    padding-top: 12px;
    padding-bottom: 12px;
  }

  .button:before,
  .button:after {
    content: "";
    display: block;
    box-sizing: border-box;
    position: absolute;
    background: var(--theme_modal_button_bg);
  }

  .button:hover,
  .button:active {
    background: var(--theme_modal_button_bg_light);
    border: 2px solid var(--theme_modal_button_border_light);
  }

  .button:hover:before,
  .button:hover:after {
    height: 2px;
    background: var(--theme_modal_button_bg_light);
  }

  .button:focus {
    border-color: none;
    box-shadow: none;
    text-decoration: none;
    outline: none;
  }

  .button:active {
    transform: scale(0.9);
  }

  .button:hover,
  .button:focus,
  .button:active {
    outline: none;
  }
</style>

问题可能是你不处理异步的方式:

    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;

someFunction()可能不是blocking1,所以下面两行会立即重置状态。 someFunction 应该 return 一个 Promise and then be awaited 这里。

  const handlClick = async () => { // mark async to await
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    await somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

REPL example

1即使是阻塞函数,数量不多,执行流程也需要打断,所以给出UI有机会更新:REPL