Trong kiến trúc hiện đại của Blazor, việc chia nhỏ giao diện thành các Component giúp mã nguồn dễ bảo trì và tái sử dụng hơn. Tuy nhiên, thách thức lớn nhất thường nằm ở việc: Làm thế nào để các Component "communicate" được với nhau?
Bài viết này sẽ giúp bạn nắm vững 3 kỹ thuật cốt lõi để truyền dữ liệu và điều khiển hành vi giữa các Component trong Blazor
1. EventCallback
EventCallback là cách chuẩn nhất để một Component con thông báo cho Component cha rằng một sự kiện nào đó đã xảy ra (ví dụ: người dùng click nút, chọn item).Giả sử bạn có 2 components: Parent và Child
Ở Component Child, bạn thêm 1 button và gọi event click của component ParentParentComponent.razor
@page "/parentcomponent"
@namespace BlazorGettingStarted.Components.Pages
@rendermode InteractiveServer
<ChildComponent Text="Tăng giá trị" OnButtonClicked="IncrementCount" />
<p>Giá trị hiện tại: @count</p>
@code {
private int count = 0;
private void IncrementCount()
{
count++;
}
}
ChildComponent.razor
@namespace BlazorGettingStarted.Components.Pages
<h3>Child Component</h3>
<button class="btn btn-primary" @onclick="HandleClick">
@Text
</button>
@code {
[Parameter]
public string Text { get; set; } = "Nhấn vào đây";
[Parameter]
public EventCallback OnButtonClicked { get; set; }
private async Task HandleClick()
{
await OnButtonClicked.InvokeAsync();
}
}
Dưới đây là sơ đồ Sequence Diagram minh họa toàn bộ cơ chế:
sequenceDiagram
participant Parent as Parent Component
participant Child as Child Component
participant User as Người dùng
Parent->>Child: Truyền [Parameter] Text
Note over Child: Hiển thị button với nội dung Text
User->>Child: Click vào button
Child->>Child: Gọi HandleClick()
Child->>Parent: OnButtonClicked.InvokeAsync()
Parent->>Parent: Chạy hàm IncrementCount()
Parent->>Parent: count++
Note over Parent: Blazor tự động render lại giao diện
2. Cascading Parameter
Nếu bạn có nhiều Component lồng nhau và muốn tất cả chúng đều truy cập được vào một dữ liệu chung (như User Info, Theme, hay App State) mà không muốn truyền qua từng cấp Parameter, hãy dùng CascadingParameter.Ví dụ: Chia sẻ Model Product
<CascadingValue Value="currentProduct">
<ProductDetails />
</CascadingValue>
@code {
private Product currentProduct = new() { Name = "Tablet", Description = "Shared model" };
}
Product Detail:
@code {
[CascadingParameter] public Product? Product { get; set; }
}
Dưới đây là đoạn code hoàn chỉnh
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
}
Product
@page "/product"
@page "/product/{id:int}"
@namespace BlazorGettingStarted.Components.Pages
@using BlazorGettingStarted.Models
@rendermode InteractiveServer
<h1>CascadingParameter Example - Product Details</h1>
<CascadingValue Value="currentProduct">
<ProductDetails />
</CascadingValue>
<hr />
<div class="mt-3">
<button class="btn btn-warning" @onclick="ChangeProduct">
Đổi sản phẩm
</button>
<a href="/product/1" class="btn btn-info ms-2">Sản phẩm 1</a>
<a href="/product/2" class="btn btn-info">Sản phẩm 2</a>
</div>
@code {
[Parameter]
public int? Id { get; set; }
private Product currentProduct = new()
{
Id = 1,
Name = "Máy tính bảng",
Description = "Thiết bị cao cấp với hiệu năng mạnh",
Price = 12500000
};
protected override void OnParametersSet()
{
// Nếu có ID trong URL, load sản phẩm tương ứng
if (Id.HasValue)
{
currentProduct = GetProductById(Id.Value);
}
}
private Product GetProductById(int id)
{
return id switch
{
1 => new Product
{
Id = 1,
Name = "Máy tính bảng",
Description = "Thiết bị cao cấp với hiệu năng mạnh",
Price = 12500000
},
2 => new Product
{
Id = 2,
Name = "Laptop Gaming",
Description = "Laptop chuyên dùng cho chơi game với GPU mạnh",
Price = 25000000
},
_ => new Product
{
Id = 0,
Name = "Sản phẩm không tìm thấy",
Description = "ID không hợp lệ",
Price = 0
}
};
}
private void ChangeProduct()
{
currentProduct = currentProduct.Id == 1
? GetProductById(2)
: GetProductById(1);
}
}
Product Detail
@namespace BlazorGettingStarted.Components.Pages
@using BlazorGettingStarted.Models
Chi tiết sản phẩm
@if (Product != null)
{
ID: @Product.Id
Tên: @Product.Name
Mô tả: @Product.Description
Giá: @Product.Price.ToString("C0") VND
}
else
{
Không có dữ liệu sản phẩm
}
@code {
[CascadingParameter]
public Product? Product { get; set; }
}
3. @ref – Điều khiển trực tiếp Child Component
Sử dụng @ref cho phép Parent Component nắm giữ một tham chiếu (reference) đến thực thể của Child Component, từ đó có thể gọi trực tiếp các hàm public.
Ví dụ
Tại Parent Component:
<!-- Liên kết thông qua biến editorRef -->
<ProductEditor @ref="editorRef" />
<button @onclick="HandleSave">Lưu từ Cha</button>
@code {
private ProductEditor? editorRef;
private void HandleSave() {
if (editorRef?.HasChanges() == true) {
editorRef.SaveChanges();
}
}
}
Tại Child Component (ProductEditor.razor):
@code {
private bool isChanged = false;
// Hàm public để cha có thể gọi
public bool HasChanges() => isChanged;
public void SaveChanges() {
// Logic lưu dữ liệu nội bộ
isChanged = false;
}
}
Sử dụng các phương thức Public
Sau khi đã "kết nối", bạn có thể gọi bất kỳ hàm nào trong ProductEditor miễn là hàm đó được đánh dấu là public.Giải thích về @bind và @bind:event
- @bind: Thiết lập liên kết dữ liệu 2 chiều. Khi giá trị trong
inputthay đổi, biến C# thay đổi và ngược lại. Mặc định kích hoạt khi mất focus (onchange). - @bind:event="oninput": Thay đổi sự kiện kích hoạt binding. Thay vì đợi mất focus, dữ liệu sẽ được cập nhật ngay lập tức sau mỗi phím gõ.
<div class="mb-3">
<label class="form-label"><strong>ID:</strong></label>
<input type="number" class="form-control" @bind="currentProduct.Id" disabled />
</div>
<div class="mb-3">
<label class="form-label"><strong>Tên sản phẩm:</strong></label>
<input type="text" class="form-control" @bind="currentProduct.Name"
@bind:event="oninput" />
</div>
<div class="mb-3">
<label class="form-label"><strong>Mô tả:</strong></label>
<textarea class="form-control" rows="3" @bind="currentProduct.Description"
@bind:event="oninput"></textarea>
</div>
<div class="mb-3">
<label class="form-label"><strong>Giá (VND):</strong></label>
<input type="number" class="form-control" @bind="currentProduct.Price"
@bind:event="oninput" />
</div>
Source code: Mediafire
4. Lời kết
Hãy linh hoạt kết hợp cả ba kỹ thuật:
- Dùng CascadingParameter cho các trạng thái toàn cục (Theme, User).
- Dùng EventCallback để giữ luồng dữ liệu minh bạch từ dưới lên trên (Data Flow).
- Dùng @ref khi cần điều khiển mang tính lệnh (Imperative) như Focus, Clear Form hoặc gọi hàm xử lý đặc biệt.
Nhận xét
Đăng nhận xét