wesocket对接vue2.0和vue3.0

该博客详细介绍了在Vue2.0和Vue3.0中如何使用WebSocket进行连接初始化、消息发送、接收及错误处理。在Vue2.0中,`mounted`和`destroyed`生命周期钩子用于打开和关闭连接,而在Vue3.0中,采用函数式组件并利用`onMounted`进行初始化。当接收到不同类型的`cmd`消息时,客户端会执行不同的业务响应,如系统通知和用户消息处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue2.0
<script>
    import store from '@/store/'

    export default {
        data() {
            return {
            }
        },
        mounted() { 
              //初始化websocket
              this.initWebSocket()
        },
        destroyed: function () { // 离开页面生命周期函数
              this.websocketclose();
        },
        methods: {
            initWebSocket: function () { // 建立连接
                // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
                var userId = store.getters.userInfo.id;
                var url = window._CONFIG['domianURL'].replace("https://","ws://").replace("http://","ws://")+"/websocket/"+userId;
                this.websock = new WebSocket(url);
                this.websock.onopen = this.websocketonopen;
                this.websock.send = this.websocketsend;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
               
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值