Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - 添加选项后刷新svelte select组件(refresh svelte select component after adding an option)

I am trying to make a select component update itself after adding an option but I can't.(添加选项后,我试图使选择组件本身进行更新,但我不能。)

Here is my code:(这是我的代码:)
<script>
  const options = ['first_option']
  const addEventSignal = () => {
    const option = prompt('Please enter new option', '')
    if (option) {
      options.push(option)
    }
  }
  const doSomething = event => {
    console.log(event)
  }
</script>

<style></style>

<div>
  <select bind:value={options} on:change={doSomething}>
    {#if options}
      {#each options as option}
        <option value={option}>{option}</option>
      {/each}
    {/if}
  </select>
  <button type="button" on:click={addEventSignal}>Add Signal</button>
</div>

If I reload the component it shows the new option but I would like to have the new option in the select list as soon as the input dialog is gone.(如果我重新加载组件,它将显示新选项,但是一旦输入对话框消失,我希望在选择列表中包含新选项。)

  ask by corneliu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Svelte doesn't detect the mutation of your options object:(Svelte不会检测到您的options对象的变异:)

options.push(option)

It only tracks assignments, with = .(它仅使用=跟踪分配。)

A very common solution to make the compiler aware of the modification is this kind of situation is self-assigment:(使编译器知道修改的一个非常常见的解决方案是这种情况是自辅助的:)
// you'd also have to make it a `let`, of course
options.push(option)

// this, Svelte will see!
options = options

You can call that a Sveltism.(您可以称其为天鹅绒主义。)

Reactivity will ensue, and your select's options should be updated immediately.(随之而来的是反应性,您选择的选项应立即更新。)

See details in this section of the tutorial.(请参阅教程本节中的详细信息。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...