Loading

Blazor笔记-Component interaction-Sharing data

更新记录

注意:非教程。纯笔记,日常查询用的。需要教程的小伙伴找几本书看看即可哈哈,有Vue基础的话非常快,概念都是通的。非工作需要不建议深入学习Blazor,深入Vue吧,用的多,哈哈。

完整目录地址:https://www.cnblogs.com/cqpanda/p/17596348.html

点击查看
2024年3月7日 发布。
2023年8月1日 迁移笔记到博客。

Component interaction-Sharing data approaches

In Blazor, data can be shared between components using three approaches:

  • CascadingParameter.
  • Parameter.
  • Transfer service.

CascadingParameter approach

CascadingParameter is a feature in Blazor that allows passing data from an ancestor component to its descendant components in a hierarchical structure. It is not able to pass data between sibling components. The following image illustrates how data flows through a component tree using CascadingParameter:

image

在祖先组件中特性修饰参数

<CascadingValue Value="@MyParameter" Name="MyParameter">
 <儿子组件/>
</CascadingValue>

[CascadingParameter]
public int MyParameter { get; set; } = 0;

在孙组件中使用

@{
  [CascadingParameter(Name="MyParameter")]
  public string MyProperty { get; set; };
}

如果有多个参数需要传递,加上Name参数即可

<CascadingValue Value="@Style1" Name="Style1">
    <CascadingValue Value="@Style2" Name="Style2">
        <子组件></子组件>
    </CascadingValue>
</CascadingValue>

@{
  public string Style1 { get; set; } = "Test Value";
  public string Style2 { get; set; } = "Test Value";
}

Parameter approach

Parameter is a feature for transmitting data from a parent component to its direct child components. However, it is essential to note that this approach does not allow passing data to sibling components or the children of the direct child. The following image illustrates how data flows through a component tree using Parameter:

image

In your child component, declare public properties that will receive the parameters passed from the parent component. You can use the [EditorRequired] attribute to mark a parameter as required. Additionally, you can set default values for the parameter by defining it in the getter and setter.

[EditorRequired]
[Parameter]
public string RequiredInputParameter { get; set; } = "";

事件

[Parameter]
public EventCallback ExampleInstanceChanged { get; set; }

Capture unmatched values

[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> AdditionalAttributes { get; set; } = new();

Transfer service approach

Transfer service is a useful approach when you want all of your components to share a common data source or adopt a "single source of truth" approach. It is not restricted by the component tree and can pass data across all components within your website. The following image illustrates how data flows through a component tree using transfer service:

image

This approach allows you to centralize the data management and keep the state of your components consistent, making your application more maintainable and easier to test.

  • Declare a transfer service
  • Consume a transfer service
posted @ 2024-03-07 15:32  重庆熊猫  阅读(5)  评论(0编辑  收藏  举报