剛開始學習blazor,據說是中小型站點全棧開發最快的,先說自己遇到的第一個問題,就是VS2022上的項目模板裡沒有blazor server應用,以為是差了啥導致的,各種折騰,包括卸載重裝之類的都沒有解決,後來搜索後才發現是因為.net 8.0中整合成blazor web app了,想使用web模式還是server模式可以自己選,所以不用糾結自己的電腦中沒有blazor server了。
![](https://news.xinpengboligang.com/upload/keji/ba13c830776a276432e7f85eb2cc4fc2.jpeg)
blazor開發本質上是組件開發,組件由html部分和C#代碼兩部分組成,組件是可以重用的,下面是一個最簡單的組件。
顯式參數
//@page "/Test" 組件名稱為Test,組件名稱第一個字母隻能為大寫
//@Title 單向數據綁定
//@code 裡面是C#代碼部分
//[Parameter] 組件參數關鍵字,在其他地方使用這個組件時,可以傳參數進來
//public string Title { get; set; } 組件具體的參數
@page "/Test"
@rendermode InteractiveServer
<h3>Test</h3>
<button onclick="">@Title</button>
@code {
[Parameter]
public string Title { get; set; }
public string Text { get; set; }
}
在home中使用test組件,可以看到,組件參數Title可以訪問到,但Text訪問不到,因為它沒有定義成組件參數,在輸入的時候會有智能提示。
![](https://news.xinpengboligang.com/upload/keji/ed7b2607a51eeb1c1389154f6dec6c7c.jpeg)
顯式參數會有智能提示
隱式參數
定義一個隱式參數,所有沒有在顯式參數中定義的,都會以鍵值對的形式添加到隱式參數中,並供組件調用。
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> addAttributes { get; set;}
@page "/Test"
@rendermode InteractiveServer
<h3>Test</h3>
<button onclick="">@Title</button>
<input @attributes="addAttributes" />
@code {
[Parameter]
public string Title { get; set; } = "";
public string Text { get; set; } = "";
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> addAttributes { get; set;}
}
在Home中調用Test組件
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
<Test Title="測試按鈕" value="組件隱式參數"></Test>
Welcome to your new app.
![](https://news.xinpengboligang.com/upload/keji/b368c0b16049a736c4cef4051af97584.jpeg)
運行後的效果
還可以這樣子聲明
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> addAttributes { get; set; } = new()
{
{"value","測試數據"},
{"text","第一行數據"}
};
級聯參數
可以從頂層組件傳遞到任意的子組件中,比如在頂層組件中設置各個子組件的主題顏色,在子組件中定義級聯參數,名稱可以隨意,但類型需要一致。
打開項目中的MainLayout.razor文件,增加如下的內容
<CascadingValue Value="@_color">
@Body
</CascadingValue>
@code
{
private readonly Theme _color = new()
{
BackgroudColor = "@a7dfdf",
FontColor = "@dff0400"
};
}
//字符串類型的級聯參數
[CascadingParameter]
public string Color { get; set; }
//新建類,用來定義一個自定義的參數
namespace BlazorApp1
{
public class Theme
{
public string FontColor { get; set; }
public string BackgroudColor { get; set; }
}
}
//自定義級聯參數的使用
<h3 style=" color:@Color.FontColor; background-color:@Color.BackgroudColor">Test</h3>
@code {
//級聯參數
[CascadingParameter]
public Theme Color { get; set; }
}
html和C#代碼的分離
要實現代碼和UI的分離,需要創建一個和組件同名的類文件,類文件會自動和組件組合在一起。
![](https://news.xinpengboligang.com/upload/keji/3c609ed2f5ab3aa71ec19c121d3cc387.jpeg)
然後就可以刪除掉Test組件中的code部分了,並且把code中的代碼轉移到test.razor.cs類中