1.引入SockJS 和Stomp
npm install sockjs-client
npm install stompjs
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
2.代码实现
data() { return { stompClient: '', timer: '' } }, mounted () { this.init() }, beforeDestroy() { // 如果跳转别的页面的时候不仍保持websocket通信,此步可注释,否则定时器要清除 //clearInterval(this.timer) this.disconnect() }, methods: { init () { this.connection() let _this = this // 断开重连机制 this.timer = setInterval( () => { try { _this.stompClient.send('test') } catch (e) { console.log('连接中断:' + e) _this.connection() } }, 10000) }, connection () { let socket = new SockJS('/vehiclemanage/websocketServer')//后端提供协议字段 this.stompClient = Stomp.over(socket) let __this = this this.stompClient.connect( {}, funct