vue 全局注册signalr
1、安装signalr
yarn add @aspnet/signalr
或
npm i --save @aspnet/signalr
2、新增signalrVue.js
const vueSignalr = {
vm: {},
// eslint-disable-next-line no-unused-vars
install(Vue, instance) {
if (this.installed) {
return;
}
this.installed = true;
if (!instance) {
// eslint-disable-next-line no-console
console.error('You have to install signalr');
return;
}
Vue.signalr = instance;
Object.defineProperties(Vue.prototype, {
signalr: {
get: function get() {
return instance;
},
},
$http: {
get: function get() {
return instance;
},
},
});
},
};
export { vueSignalr };
3、新增signalr.js
import * as signalR from '@aspnet/signalr';
import config from '@/config';
import { vueSignalr } from './signalrVue';
import Vue from 'vue';
let vm = new Vue({});
const connection =new signalR.HubConnectionBuilder()
.withUrl(config.signalR.url)
//.withAutomaticReconnect([0, 0, 10000])
//.configureLogging(signalR.LogLevel.Information)
.build();
// 监听关闭异常
connection.onclose(err => {
console.assert(connection.state === signalR.HubConnectionState.Disconnected);
vm.$message.error(err);
});
const start = function() {
if (connection.state != signalR.HubConnectionState.Connected) {
connection
.start()
.then(() => {
// 服务连接成功,自动注册一下
register;
})
.catch(err => {
vm.$message.error(err);
});
}
};
const register = function() {
connection
.invoke('Register', 'default')
.then()
.catch(err => {
vm.$message.error(err);
});
};
start();
// 添加插件
const installer={
vm:{},
install(Vue){
Vue.use(vueSignalr, connection);
}
}
export { installer as VueSignalr, connection as signalr };
4、main.js 文件中引入
import { VueAxios } from './utils/axios';
Vue.use(VueAxios);
// 其他模块使用
function(){
this.signalr.on("Method",function(){
// receive message
})
}