1、安装
npm install sockjs-client
npm install stompjs
2、引用
我这边是一个地方使用
直接组件内引用
import Stomp from 'stompjs'
import specialTreatment from './specialTreatment'
3、使用
connection(){
//初始化weosocket
// 定义客户端的认证信息,按需求配置
// 获取STOMP子协议的客户端对象
let socket = new SockJS(`http://**.**.**.**:8081/endpoint`); //接口地址
const stompClient = Stomp.over(socket);
this.stompClient = stompClient
stompClient.debug = null;
const useName = window.sessionStorage.getItem('userName')
let headers = {
//请求需要携带的一些入参
username:useName
}
const _this = this
// 向服务器发起websocket连接
stompClient.connect(headers,() => {
stompClient.subscribe(`msg/spInfo`, (msg) => {
// 订阅服务端提供的某个topic
const dataList = JSON.parse(msg.body) || {
} // 返回的是json串,需要parse一下
if(_this.specialTreatmentArr.length>0){
//信息有多条时保存到消息队列
this.specialTreatmentArr.push(dataList)
}else{
_this.dialogVisible = true
this.specialTreatment = dataList
this.modification = JSON.parse(JSON.stringify(dataList.vehicleView || {
}))
this.specialTreatmentArr.push(dataList)
}
console.log(this.specialTreatmentArr,'this.specialTreatmentArr')
})
}, (err) => {
// 连接发生错误时的处理函数
console.log('失败')
console.log(err);
this.$router.push('/login')
})
},
disconnect() {
if (this.stompClient) {
this.stompClient.disconnect();
}
}, // 断开连接
destroyed() {
// this.websocketclose() //离开路由之后断开websocket连接
this.disconnect()
},