工作中遇到了,记录下
先下载插件
npm install stompjs
在组件中引用
程序代码
destroyed(){
this.disconnect()
},
methods:{
onConnected(frame) {
console.log("Connected: " + frame);
var topic = 'stomp'+ this.deviceCode; //订阅地址
this.client.subscribe(topic, this.responseCallback,{
'x-queue-name': 'stomp'+ this.deviceCode, //通道序列名
'durable': false,
'exclusive': false,
'auto-delete': false
});
},
onFailed(frame) {
console.log("Failed: " + frame);
this.$message.error("连接异常中断!尝试重新启动或者联系管理员!")
},
responseCallback(frame) {
let val=JSON.parse(frame.body)
this.list.push(JSON.parse(val)) //处理得到的消息
},
connect() {
this.client= Stomp.client('ws://'+ this.host +':15674/ws') //填写地址,ws://+ip+端口+/ws
this.client.connect("stomp","stomp", this.onConnected, this.onFailed); //参数依次为:用户名,密码,连接后,出错
},
open(){ //启动连接
this.connect()
},
disconnect(){ //关闭连接
if(this.client && this.client.connected) {
this.client.disconnect( () => {
this.subscribes = {};
})
}
}
}
页面关闭同时也退出连接