1.websocket 連接代碼
created() { this.initWebsocket() }, methods: { // 初始化websocket initWebsocket() { let _this = this let ws = new WebSocket(this.wsUrl) //保持連接 ws.onopen = () = > { // Web Socket 已連接上,使用 send() 方法發送數據 //console.log('數據發送中...') setInterval(() = > { let msg = { msg: '心跳內容' } ws.send(JSON.stringify(msg)) }, 5000) //console.log('數據發送完成') } //數據接收 ws.onmessage = evt = > { _this.websocketonmessage(evt) //console.log('數據已接收...') } // 關閉 websocket 時的 鈎子 ws.onclose = () = > { //console.log('連接已關閉...') _this.websocket() } // 路由跳轉時結束websocket鏈接 this.$router.afterEach(() = > { ws.close() }) },//數據接收 websocketonmessage(e) { // 數據處理 let obj = JSON.parse(e.data) } }