Blazor组件:从子组件更新模型时刷新父组件 [英] Blazor component : refresh parent when model is updated from child component

查看:309
本文介绍了Blazor组件:从子组件更新模型时刷新父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP.NET Core 3预览版4中使用服务器端Blazor组件.

I'm using Server-side Blazor components in ASP.NET Core 3 preview 4.

我有一个父组件和一个子组件,它们使用相同的共享模型,如下所示:

I have a parent component, and child components, using the same shared model, like this :

型号:

public class CountModel
{
    public int Count { get; set; }

    public void Increment()
    {
        Count++;
    }
}

父组件:

@page "/count"

<CascadingValue Value="currentCount">
    <h1>Count parent</h1>

    <p>Current count is : @currentCount.Count</p>

    <button class="btn btn-primary" onclick="@currentCount.Increment">+1 from parent</button>

    <CountChild></CountChild>
</CascadingValue>

@functions {
    private CountModel currentCount = new CountModel();
}

子组件:

<h1>Count child</h1>

<p>Current count is : @currentCount.Count</p>

<button class="btn btn-primary" onclick="@currentCount.Increment">+1 from child</button>


@functions {
    [CascadingParameter]
    private CountModel currentCount { get; set; }
}

这是用于父代和子代的模型的同一实例. 从父级更新模型时,两者均显示正确的增量值. 从子级更新时,只有子级显示正确的值.

It's the same instance of the model used for the parent and the child. When the model is updated from the parent, both display the correct incremented value. When it's updated from the child, only the child display the correct value.

从子级更新父组件时,如何强制刷新它?

How can I force the parent component to be refreshed when it is updated from the child ?

注意,这里我有一个更新模型的功能,但是当数据绑定到输入时,我希望该解决方案能起作用.

Note, here I have a function to update the model, but I would like the solution to work when data is bound to an input.

推荐答案

创建共享服务.在父项中订阅服务的"RefreshRequested"事件,并从子项中订阅Invoke().在父方法中,调用StateHasChanged();

Create a shared service. Subscribe to the service's "RefreshRequested" event in the parent and Invoke() from the child. In the parent method call StateHasChanged();

public interface IMyService
{
 event Action RefreshRequested;
 void CallRequestRefresh;
 }

public class MyService: IMyService
{
    public event Action RefreshRequested;
    public void CallRequestRefresh()
    {
         RefreshRequested?.Invoke();
    }
}


//child component
MyService.CallRequestRefresh();


//parent component
MyService.RefreshRequested += RefreshMe;

private void RefreshMe()
{
    StateHasChanged();
}

这篇关于Blazor组件:从子组件更新模型时刷新父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆