5

.NET 8新预览版本使用 Blazor 组件进行服务器端呈现 - tokengo

 1 year ago
source link: https://www.cnblogs.com/hejiale010426/p/17309490.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.NET 8新预览版本使用 Blazor 组件进行服务器端呈现

此预览版添加了对使用 Blazor 组件进行服务器端呈现的初始支持。这是 Blazor 统一工作的开始,旨在使 Blazor 组件能够满足客户端和服务器端的所有 Web UI 需求。这是该功能的早期预览版,因此仍然受到一定限制,但我们的目标是无论选择如何构建应用,都能使用可重用的 Blazor 组件。

服务器端呈现 (SSR) 是指服务器生成 HTML 以响应请求。使用 SSR 的应用加载速度很快,因为渲染 UI 的所有艰苦工作都在服务器上完成,而无需下载大型 JavaScript 捆绑包。ASP.NET Core 对带有 MVC 和 Razor 页面的 SSR 现有支持,但这些框架缺乏用于构建可重用的 Web UI 片段的组件模型。这就是开拓者的用武之地!我们正在添加对使用 Blazor 组件生成服务器呈现的 UI 的支持,这些组件也可以扩展到客户端以实现丰富的交互性。

在此预览版中,可以使用 Blazor 组件执行服务器端呈现,而无需任何 .cshtml 文件。框架将发现可路由的 Blazor 组件,并将其设置为终结点。不涉及 WebAssembly 或 WebSocket 连接。你不需要加载任何JavaScript。每个请求由相应终结点的 Blazor 组件独立处理。

首先需要安装 .NET 8预览版最新版

1.创建一个空的 ASP.NET Core web app:

dotnet new web -o WebApp
cd WebApp
  1. 在项目中添加一个简单的Razor组件:
dotnet new razorcomponent -n MyComponent
  1. 更新MyComponent.razor内容,将其变成一个带有路由的合适的HTML页面;
@page "/"
@implements IRazorComponentApplication<MyComponent>

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Hello Blazor!</h1>
    <p>The time is @DateTime.Now.ToShortTimeString()</p>
</body>
</html>

你还需要在这个组件上实现接口IRazorComponentApplication,该接口目前用于帮助发现应用程序中的组件端点。这个设计可能会在以后的更新中改变,但目前这个接口是必需的。

  1. Program.cs中通过调用.AddRazorComponents()设置Razor组件服务

    builder.Services.AddRazorComponents();
    
  2. 通过调用映射组件的端点。你需要为你的组件添加一个using指令:MapRazorComponents<TComponent>()

app.MapRazorComponents<WebApp.MyComponent>();

可路由组件将自动在所驻留的程序集中发现。再次注意,当前必须实现,但此设计可能会在以后的更新中更改。MyComponentTComponentIRazorComponentApplication

  1. 运行应用程序并浏览到应用程序根目录查看你的组件渲染
2415052-20230412131803932-183788183.png

但是似乎无法交互,我在使用了点击事件但是没法触发了

修改MyComponent.razor文件代码

@page "/"
@implements IRazorComponentApplication<MyComponent>

<!DOCTYPE html>
<html lang="en">

<body>
    <h1>Hello Blazor!</h1>
    <p>The time is @DateTime.Now.ToShortTimeString()</p>
    <p>Counter: @counter</p>
    <button @onclick="OnClick">run</button>
    @code {
        private int counter = 0;
        private void OnClick()
        {
            counter++;
        }
    }
</body>

</html>

运行效果:

2415052-20230412131757857-2017323472.png

当我们点击按钮并不会触发事件!可能是需要写js去完成,欢迎大佬一块讨论讨论新的技术

来着token的分享

技术交流:737776595

本文作者:tokengo

本文链接:https://www.cnblogs.com/hejiale010426/p/17309490.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK