Difference between @bind and @bind-value

前端 未结 2 705
再見小時候
再見小時候 2021-02-18 16:56

What is the difference of using @bind and @bind-value?

I made this simple example, and testing it in the browser, I didn\'t see any difference.

2条回答
  •  无人及你
    2021-02-18 17:00

    Short Version

    @bind is an override of @bind-value with the event set to "onchange".

    These two commands are equivalent:

     ... @bind-value="userName" @bind-value:event="onchange" ...
     ... @bind="userName" ...
    

    Long Version

    The @bind attribute accomplishes two separate (but related) tasks:

    1. Binds an expression to the value of the component
    2. Binds a delegate that will trigger the component's ValueChanged property

    Both the expression and the delegate are required. An implementation of @bind-Value looks like this:

     ... @bind-value="userName" @bind-value:event="onchange" ...
    

    We are setting both the expression (="userName") and the delegate (="onchange").

    The "easier" @bind= is just an override with the delegate preset to "onchange". So these two commands are functionally the same:

     ... @bind-value="userName" @bind-value:event="onchange" ...
     ... @bind="userName" ...
    

    A greatly simplified analogy using overriding methods:

    public void bind-value(string value, string event)
    {..}
    
    public void bind(string value)
    {
      bind-value(value, "onchange");
    }
    

    A couple of common use-cases for using the full @bind-value version are

    1. updating the UI as the user types
    2. validating an email address as the user types

    Remember, the onchange event will only trigger PropertyChanged when the component loses focus. Instead, we want PropertyChanged to be triggered by the oninput event:

    ... @bind-value="H1Content" @bind-value:event="oninput" ...
    ... @bind-value="email" @bind-value:event="oninput" ...
    

提交回复
热议问题