Blazor 是一个使用 C#、HTML 和 CSS 构建交互式 Web UI 的开源框架,支持服务器端和客户端运行,允许开发者利用 C# 和 .NET 生态来创建 Web 应用。
🌱Create
carete Blazor Web
Program.cs 是启动服务器以及在其中配置应用服务和中间件的应用的入口点。
在 Components 目录中:
App.razor 为应用的根组件。
Routes.razor 配置 Blazor 路由器。
Pages 目录包含应用的一些示例网页。
BlazorApp.csproj 定义应用项目及其依赖项,且可以通过双击解决方案资源管理器中的 BlazorApp 项目节点进行查看。
Properties 目录中的 launchSettings.json 文件为本地开发环境定义不同的配置文件设置。创建项目时会自动分配端口号并将其保存在此文件上。
🪴Run
pages home.razor
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world m qqqqq</h1>
hihihi
🌴Counter
counter.razor
@page "/counter"
@rendermode InteractiveServer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
🌲Weather
像Vue
🌳Component
home > component
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world m qqqqq</h1>
hihihi
<Counter />
<Weather> </Weather>
Parameter
修改counter
@code {
private int currentCount = 0;
[Parameter]
public int IncrementAmount { get; set; } = 1;
private void IncrementCount()
{
// currentCount++;
currentCount += IncrementAmount;
}
}
<Counter IncrementAmount="2" />
点击即增加2
data
<input @bind="text" />
<button @onclick="() => text = string.Empty">Clear</button>
<p>@text</p>
@code {
string text = "";
}
🌻ToDoList
nav
Components/Layout/NavMenu.razor
<div class="nav-item px-3">
<NavLink class="nav-link" href="todo">
<span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Todo
</NavLink>
</div>
TodoItem
public class TodoItem
{
public string? Title { get; set; }
public bool IsDone { get; set; } = false;
}
AddItem
<ul>
@foreach (var todo in todos)
{
<li>@todo.Title</li>
}
</ul>
<br />
<input @bind="newTodo" />
<button @onclick="AddTodo">Add todo</button>
@code {
private List<TodoItem> todos = new();
string newTodo = "";
void AddTodo()
{
if (!string.IsNullOrWhiteSpace(newTodo))
{
todos.Add(new TodoItem { Title = newTodo });
newTodo = string.Empty;
}
}
}