Vue客户端
vue-cli已经把项目搭建起来了 首先在终端安装一下signalR插件
npm install @microsoft/signalr
在需要的地方直接引入
import * as signalR from "@microsoft/signalr";
export default {
data() {
return {
connection: null,
msgs: [],
dataInfo: { status1: "off", status2: "off" }
}
},
created(){
this.connection = new signalR.HubConnectionBuilder()
.withUrl("http://10.1x.xx.xx:xxxx/abcd") // 此处填服务器地址
.withAutomaticReconnect() // 断开自动重连
.build();
// -- 这地方二选一 -- ( 不要全拿走复制粘贴 )
// (1)注册方法( 给后端调用的,需要在methods中定义 )
this.connection.on("showmsg", this.ShowMsg);
this.connection.on("updatedata", this.UpdateData);
// (2)或者也可以是下面这种 二选一
this.connection.on("change", (message) => {
// 打印直接可以看到你的数据返回 ( methods里面不需要再定义 )
console.log("change数据内容 -->", JSON.parse(message));
});
// 开始连接
this.connection
.start()
.then((res) => console.log("Connected!"))
.catch((err) => {
console.log(err);
});
},
methods:{
ShowMsg(msgInfo) {
this.msgs.push(msgInfo);
},
UpdateData(dataMsg) {
this.dataInfo = dataMsg;
},
// 调用后端方法(直接调用invoke注入,需要和后端对接方法名及参数)
receiveMessage() {
let params = "Hello";
this.connection
.invoke("TestMsg", params) // invoke(方法名, 参数)
.then(() => console.log("send succeed!"));
}
},
watch:{
},
computed:{
}
}
这一趴把你自己的服务器地址填写对就ok了 剩下你就完全可以复制粘贴了 该解释的 上面注释都解释了!!!!
--------------------------------------------如果安装插件的时候报错------------------------------------------------
你可以尝试一下清空一下缓存
$ npm config set proxy null
$ npm config set https-proxy null
然后配置一下淘宝镜像
# 淘宝源(推荐)
$ npm config set registry http://registry.npm.taobao.org/
然后这个时候你在重新下载一下 npm install @microsoft/signalr 应该就ok了