问题描述
我有一个简单的双向绑定组件:
I have a simple two-way binded component:
<input type="text" id="myInput" bind="@MyVar" />
...
@functions {
private string MyVar { get; set; } = "foo";
当我在输入框上输入文本时,一切运行正常.但是,如果从javascript设置了输入值,那么blazor将无法检测到更改后的值.
All runs fine when I write text on input box. But, if input value is set from javascript then blazor is no able to detect the changed value.
document.getElementById('myInput').value='Random Value';
我试图在元素上引发一些事件,例如按下键",所以私有var MyVar在blazor客户端没有任何变化.
I tried to raise some events on element like 'key pressed' and so but the private var MyVar has no changes on blazor client side.
我想向客户端发送一些值,我想更改隐藏输入的值可能是解决方案,但不起作用.
I would like to send back to blazor some values from client, I guess changing value of a hidden input may be solution, but not working.
推荐答案
随着Blazor将自身附加到onchange事件上,可以通过在设置元素后触发元素上的"onchange"事件来使其工作. >
As Blazor attaches itself to the onchange event you can make this work by triggering the 'onchange'-event on the element after you've set it.
var element = document.getElementById('myInput');
element.value = 'Random Value';
element.dispatchEvent(new Event('change')); //<--makes Blazor see the change
在许多情况下,当您可以使用现有的javascript库时,无需重新设计所有东西.
There is in many cases no need to reinvent everything when you can use existing javascript-libraries.
这篇关于从JS更新时未检测到Blazor双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!