【问题标题】:Svelte: How to stop the {#await} block from getting refreshed every time the bound attribute is changed?Svelte:每次更改绑定属性时,如何阻止 {#await} 块刷新?
【发布时间】:2019-11-16 10:29:00
【问题描述】:

我正在尝试使用从基于 Promise 的函数获得的数据初始化 <select/> 输入。在输入初始化选项之后(每个选项从解析的数据中获取值和标签),一个属性被绑定到<select/>。

但每次我更改选项(使用属性绑定)时,{#await} 块内的所有内容都会重新加载(似乎它解决了相同的 Promise 并重置选项)。

当我删除绑定时不会发生这种情况。

我尝试了以下方法:

  • 尝试将属性绑定到选择。

    `<select bind:value={selected_device}>...`
    
  • 尝试绑定从列表中获取所选选项的事件。

    `<select on:change={set_selected_device}>...`
    
  • 尝试制作另一个按钮以获取所选选项。

    <select>...</select>
    <button on:click={set_selected_device}>Set</button>`
    

这是当前状态的sn-p:

等待块:

<div class="device-select container">
  {#await VoiceStreamingService.get_microhpones()}

  {:then devices}
    <select id="device-options">
      <option selected disabled>Select an Option...</option>
      {#each devices as device (device.deviceId)}
        <option value={device.deviceId}>{device.label}</option>
      {/each}
    </select>
  {:catch}

  {/await}
  <button on:click={set_selected_device}>Connect To</button>
</div>

set_selected_device 函数:

function set_selected_device() {
    let d = document.getElementById("device-options");
    selected_device = d.options[d.selectedIndex].value;
    console.log(selected_device);
  }

我错过了什么重要的东西,还是一个错误?

【问题讨论】:

    标签: svelte svelte-component


    【解决方案1】:

    恐怕这是一个错误:https://github.com/sveltejs/svelte/issues/2355

    一种解决方法是在脚本中创建一个变量...

    let promise = VoiceStreamingService.get_microhpones();
    

    并等待它而不是表达式。

    【讨论】:

    • 感谢 Rich 的建议。我试过了。我会发布我的答案。
    【解决方案2】:

    我尝试在安装组件后解决承诺,然后将选项推送到选择对象。

    分享以下代码:

    onMount(() => {
      (async () => {
        let select = document.getElementById("device-options");
        try {
          (await VoiceStreamingService.get_microhpones()).forEach(device => {
            let option = document.createElement("option");
            option.value = device.deviceId;
            option.innerHTML = device.label;
            select.appendChild(option);
          });
        } catch (e) {
          console.log(e);
        }
      })();
    });
    

    【讨论】:

    • 您最好使用 Svelte 的数据绑定,而不是查询和操作 DOM。 onMount 函数本身可以是异步的,因此您可以执行 let devices; onMount(async () =&gt; devices = await ...) 之类的操作
    • 关于 onMount 部分要好得多。但是你能解释一下数据绑定吗?因为我不明白如何将解析的数组绑定到一个`select`对象。 (在设备解析之前调用 {#each} 指令)
    • 我应该说let devices = [];——即将它初始化为一个空数组,一旦承诺解决,它就会被设备列表替换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多