【问题标题】:Svelte does not update value in one if branchSvelte 不会在一个 if 分支中更新值
【发布时间】:2021-04-21 12:56:53
【问题描述】:

我正在尝试在 Svelte 中实现一些货币输入。

几乎所有东西都可以例外,但如果我删除带有Backspace 的字段中的输入,我可以看到日志消息,但该值未设置为'0.00'

我为此准备了一个 REPL:https://svelte.dev/repl/2b83934eff9747a1a1c7a15c976be316?version=3.31.2

<script>
  let amountFormatted = '0.00';
  let currencyInput;
 
  $: console.log('amountFormatted: ' + amountFormatted);

   const handleChange = () => {
     console.log('currentInput: ' + currencyInput.value);

     let cleanedInput = currencyInput.value
      .replace(/\D*/gm, '') // remove non digits
      .replace(/^0+/gm, ''); // remove leading zeros 
     console.log('cleanedInput.length: ' + cleanedInput.length);

    if (cleanedInput.length === 0 ) {
      console.log('setting amountFormatted to 0.00 --- BUT IT does not work ');
      amountFormatted = '0.00'; // ERROR this never works
    } else {
      amountFormatted = (parseInt(cleanedInput, 10) / 100).toString();
    }
  };
</script>

<input
    type="tel"
    value={amountFormatted}
    bind:this={currencyInput}
    on:input={handleChange}
/>

我几乎要花一整天的时间来完成这项工作。我尝试了诸如tick() 之类的东西以及许多其他东西,但似乎amountFormatted = '0.00'; 从未触发过响应式更改。

【问题讨论】:

  • currencyInput.value = '0.00'; 做这个工作
  • 是的,现在可以了。非常感谢。但我仍然很好奇为什么其他方法不起作用!但是我要非常感谢你!!!

标签: svelte svelte-3


【解决方案1】:

一种方法是使用bind 工作

<input
    type="tel"
    bind:value={amountFormatted} // Not sure why without bind is not working, need to explore
    bind:this={currencyInput}
    on:input={handleChange}
/>

或者第二个:

   if (cleanedInput.length === 0 ) {
      console.log('setting amountFormatted to 0.00 --- BUT IT does not work ');
      currencyInput.value = '0.00'; // this works
    } else {
      amountFormatted = (parseInt(cleanedInput, 10) / 100).toString();
    }

<input
    type="tel"
    value={amountFormatted}
    bind:this={currencyInput}
    on:input={handleChange}
/>

根据Svelte REPL,我了解到对于numeric inputs

value={somevaribale} is one way binding

bind:value={somevaribale} is two way binding.

【讨论】:

  • 如果没有bind,输入值不会更新,需要检查一下。
  • 如果你知道它为什么会这样,请告诉我
  • 如果我知道我会的。但由于今天是我与 Svelte 的第一天,我不能保证会找到解决方案;)
  • 是的,我也是新手,但想通了,这是绑定问题,更新了我的答案,检查 REPL
  • 不确定。因为在 else 分支中它起作用了。即使没有bind:value.
猜你喜欢
  • 2021-10-03
  • 2019-09-21
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 2021-02-19
  • 2011-04-07
  • 2021-07-23
  • 2021-02-20
相关资源
最近更新 更多