vue项目开发在页面切换之后需要主动的将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()
}

websocket封装

新建websocket.js

项目中直接引用:

import {socketSend,socketConnectfrom "../../components/Flow/websocket.js";

模块化代码:

export function socketConnect(_this) {
    let websocketUrl = "ws://127.0.0.1:1626/?username=bsEditor&password=123456";
    let ws = new WebSocket(websocketUrl);
    ws.onopen = function () {
        // Web Socket 已连接上,使用 send() 方法发送数据
        console.log('数据发送中...')
    },
        ws.onmessage = function (e) {
            let toFrom = '';
            //数据接收
            console.log("数据接收开始");
        },
        ws.onclose = function () {
            // 关闭 websocket
            console.log('连接已关闭...')
        },
        // 组件销毁时调用,中断websocket链接
        _this.socketOver = () => {
            ws.close()
        }
    _this.websocket = ws;

}
export function socketSend(typewsContentresult_this) {
    _this.websocket.socketSend = function (typewsContentresult) {
        let wsData = {};
        wsData = {
            "chatType": type,//1:单聊;2:群聊
            "cmd": 11,
            "content": {
                "result": result//执行成功或者失败 
                "message": wsContent //执行返回的信息
            },
            "createTime": "",
            "from": "bsEditor",
            "groupId": "1625",
            "msgType": "0",

        }

        _this.websocket.send(JSON.stringify(wsData));

    }
    _this.websocket.socketSend(typewsContentresult);
}