I found that $attrs in vue is a very helpful thing in component design. If I have a component wrapping an "a" tag, I could use $attrs to pass in all those native props without claiming them as parameters one by one. For example, I have a component like this:
<div>
<a href="@Href" onclick="@OnClick" class="@Classes" style="@Styles">@Content</a>
</div>
I have to declare parameters of "Href, OnClick, Classes, Styles" and so forth. But we know that tag "a" has huge amount of other attributes, like "target, hreflang...", not to mention "input" tag or so. I think it's stupid to claim all of them as a unbelievable long parameter list.
So dose Blazor provide such similar function for us developers?
Yes, it does.
You can use Blazor’s new ‘splat’ operator to do this. For example:
// MyComp
<div id=“@Id” @attributes=“InputAttributes”></div>
@code {
[Parameter]
public string Id { get; set; }
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> InputAttributes { get; set; }
}
Defining a parameter per the example above will make it collect any attributes defined on the component which don’t match any existing declared parameters.
Usage:
<MyComp Id=“foo” class=“myclass” />
Would render:
<div id=“foo” class=“myclass”></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With