.NET Core 和 Vue3 结合使用 SignalR 可以实现强大的实时通讯功能,允许实时双向通信。在这个示例中,我们将详细说明如何创建一个简单的聊天应用程序,演示如何使用 .NET Core SignalR 后端和 Vue3 前端来实现实时通讯功能。
确保你已经安装了以下工具和环境:
首先,让我们创建一个 .NET Core SignalR 后端应用程序。
dotnet new web -n SignalRChatApp
cd SignalRChatApp
dotnet add package Microsoft.AspNetCore.SignalR
// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace SignalRChatApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});
}
}
}
// ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRChatApp
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
现在,我们将创建一个 Vue3 前端应用程序,以连接到 SignalR 后端。
vue create vue-signalr-chat
选择默认配置或根据需要进行配置。
npm install @microsoft/signalr
<!-- src/components/Chat.vue -->
<template>
<div>
<div>
<input v-model="user" placeholder="Enter your name" />
</div>
<div>
<input v-model="message" @keyup.enter="sendMessage" placeholder="Type a message" />
</div>
<div>
<div v-for="msg in messages" :key="msg" class="message">{{ msg }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
user: "",
message: "",
messages: [],
};
},
mounted() {
this.connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
this.connection.start().then(() => {
this.connection.on("ReceiveMessage", (user, message) => {
this.messages.push(`${user}: ${message}`);
});
});
},
methods: {
sendMessage() {
if (this.user && this.message) {
this.connection.invoke("SendMessage", this.user, this.message);
this.message = "";
}
},
},
};
</script>
<style scoped>
.message {
margin: 5px;
}
</style>
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<Chat />
</div>
</template>
<script>
import Chat from "@/components/Chat.vue";
export default {
name: "Home",
components: {
Chat,
},
};
</script>
dotnet run
npm run serve
现在,你的 SignalR 实时聊天应用程序应该已经运行了。打开浏览器,访问 `https://
localhost:8080`,输入用户名,开始聊天。
这个示例演示了如何使用 .NET Core SignalR 后端和 Vue3 前端创建一个简单的实时聊天应用程序。你可以根据需要扩展该应用程序,添加更多功能和样式。此外,你还可以使用 SignalR 来构建更复杂的实时应用程序,如实时通知、在线游戏和协同编辑等。