Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)5.8k · #14564

coordinate-components

Skill này làm gì

Skill này chỉ cách chia sẻ dữ liệu giữa các component Blazor không liên kết trực tiếp, ví dụ số lượng giỏ hàng hiển thị trên nhiều trang. Skill dành cho lập trình viên .NET xây dựng giao diện Blazor có trạng thái dùng chung.

Khi nào nên dùng

  • ✓Khi số lượng sản phẩm trong giỏ hoặc huy hiệu thông báo phải hiển thị trên nhiều trang.
  • ✓Khi một chủ đề hoặc người dùng hiện tại cần đến các component nằm trong một layout.
  • ✓Khi hai component xa nhau trên trang cần phản ứng với cùng một thay đổi.

Liên kết skill

https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/coordinate-components/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/coordinate-components/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Hiển thị số lượng sản phẩm trong giỏ ở header và cập nhật từ bất kỳ trang sản phẩm nào trong ứng dụng Blazor của tôi.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent chọn cơ chế phù hợp với phạm vi, như cascading value cho một layout hoặc service dùng chung có scoped và sự kiện thay đổi, rồi kết nối và giải phóng đúng cách.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Coordinate Components

Step 1 — Read AGENTS.md

Read AGENTS.md at the workspace root to learn the project's conventions before making changes.

Step 2 — Decide the scope

Need Mechanism When to use
Subtree (same render mode) CascadingValue component Theme, layout config within a layout
App-wide (all render modes) CascadingValueSource<T> via DI Current user, feature flags, theme shared globally
Mutable shared state within a circuit Scoped service + Action event Shopping cart, notification count, selected filters

For parent→child one level: use [Parameter] / EventCallback (see author-component skill). For persisting state across prerender→interactive: see support-prerendering skill.

Workflow (quick reference)

  1. Choose the mechanism from the table in Step 2
  2. If crossing render mode boundaries → use CascadingValueSource<T> (Step 4)
  3. Register in Program.cs with AddCascadingValue(...) and isFixed: false
  4. Consume via [CascadingParameter] in child components
  5. Update via NotifyChangedAsync(newValue) — never page reload
  6. For additional mutable state within a circuit → add scoped service (Step 5)
  7. Wrap any StateHasChanged from background threads in InvokeAsync
  8. Implement IDisposable — dispose timers, cancel tokens, unsubscribe events

Step 3 — CascadingValue for subtree state

Wrap a subtree with <CascadingValue> to flow data to all descendants without passing it through every intermediate component.

@* In a layout or parent component *@
<CascadingValue Value="theme">
    @Body
</CascadingValue>

@code {
    private ThemeInfo theme = new() { ButtonClass = "btn-primary" };
}

Consume in any descendant:

[CascadingParameter]
private ThemeInfo? Theme { get; set; }

Rules:

  • Matched by type, not name. To cascade multiple values of the same type, add Name:
    <CascadingValue Value="primary" Name="PrimaryTheme">...</CascadingValue>
    
    [CascadingParameter(Name = "PrimaryTheme")]
    private ThemeInfo? Primary { get; set; }
    
  • Set IsFixed="true" when the value never changes — avoids subscription overhead.
  • Does NOT cross render mode boundaries. A <CascadingValue> in a static SSR parent is invisible to interactive children. See Step 6.

Step 4 — CascadingValueSource<T> for app-wide state

Register a CascadingValueSource<T> in DI when the value must be available to all components regardless of render mode.

// Program.cs
builder.Services.AddCascadingValue(sp =>
{
    var theme = new ThemeInfo { ButtonClass = "btn-primary" };
    return new CascadingValueSource<ThemeInfo>(theme, isFixed: false);
});

Consume identically to Step 3:

[CascadingParameter]
private ThemeInfo? Theme { get; set; }

To update and notify subscribers, either mutate the existing object or replace it:

@* Component that changes the theme *@
@inject CascadingValueSource<ThemeInfo> ThemeSource

<button @onclick="ToggleDarkMode">Toggle theme</button>

@code {
    private bool isDark;

    private async Task ToggleDarkMode()
    {
        isDark = !isDark;
        // Replace the value entirely:
        var newTheme = new ThemeInfo { ButtonClass = isDark ? "btn-dark" : "btn-primary" };
        await ThemeSource.NotifyChangedAsync(newTheme);
    }
}

NotifyChangedAsync() (no argument) also works — mutate the object and then call it. NotifyChangedAsync(newValue) replaces the value and notifies in one step.

Update protocol: Whenever shared state changes, the component that changes it MUST inject CascadingValueSource<T> and call NotifyChangedAsync(). This is the only mechanism that triggers re-rendering in all [CascadingParameter] subscribers. Without this call, no subscribers update. Do not use NavigationManager.Refresh() or page reloads as a substitute.

Rules:

  • isFixed: false enables change notifications. isFixed: true is better for truly static values (feature flags).
  • Crosses render mode boundaries — works for per-page interactivity, global interactivity, and WebAssembly. Key advantage over <CascadingValue>.
  • Keep cascaded types granular. Every NotifyChangedAsync re-renders ALL subscribers regardless of which property changed. Don't put all app state into one cascaded type.
  • For Auto/WebAssembly apps, register in both server and .Client Program.cs. The typ
Câu hỏi thường gặp

Cascading state là gì?

Đó là cách truyền một giá trị xuống một phần của cây component mà không phải truyền qua từng tham số.

Skill có hoạt động qua các chế độ render không?

Có. Skill bao quát việc chia sẻ trạng thái qua ranh giới các chế độ render.

Skill có dọn dẹp các subscription không?

Có. Skill bao gồm giải phóng timer, token hủy và sự kiện.

Chi tiết

Mô tả gốc của tác giả

Share state between components that don't have a direct parent-child parameter relationship, using cascading values, scoped services with change events, or CascadingValueSource via DI. USE WHEN the user needs a CascadingParameter or CascadingValue that works across render mode boundaries, a shopping cart or notification count accessible from multiple pages, a theme or user preference cascaded app-wide, or when components in different parts of the tree must react when shared data changes. Also USE WHEN cascading values aren't reaching interactive children in per-page interactivity mode, or when

repo: dotnet/skills

Độ phổ biến

Sao GitHub
5.8k
Vị trí xếp hạng
#14564
Giấy phép
MIT
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự