1. 程式人生 > >vue2.0在使用websocket時切換頁面後websocket依舊保持連線

vue2.0在使用websocket時切換頁面後websocket依舊保持連線

在頁面切換之後需要主動的將websocket進行斷開操作
在methods中定義websocket函式
方法一:

 websocket () {
     let ws = new WebSocket('ws://localhost:8080')
     ws.onopen = () => {
        // Web Socket 已連線上,使用 send() 方法傳送資料
          ws.send('Holle')
          console.log('資料傳送中...')
      }
      ws.onmessage = evt => {
        // console.log('資料已接收...')
} ws.onclose = function () { // 關閉 websocket console.log('連線已關閉...') } // 路由跳轉時結束websocket連結 this.$router.afterEach(function () { ws.close() }) }

方法二:

methods: {
    websocket () {
         let ws = new WebSocket('ws://localhost:8080')
         ws.onopen
= () =>
{ // Web Socket 已連線上,使用 send() 方法傳送資料 ws.send('Holle') console.log('資料傳送中...') } ws.onmessage = evt => { // console.log('資料已接收...') } ws.onclose = function () { // 關閉 websocket console
.log('連線已關閉...') } // 元件銷燬時呼叫,中斷websocket連結 this.over = () => { ws.close() } } }, beforeDestroy () { this.over() }