亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Vue中使用websocket的正確使用方法

第一次使用websocket就是需要在vue中去使用他,在网上搜索了很多如何在vue中使用的教程和示例,有些demo过于简单扩展性太差,有些存在bug

网上经常被搜索到的一个答案是这个https://blog.csdn.net/niyuelin1990/article/details/78062139#commentsedit,但是这个答案中在解决websocket未开启和正在开启状态的处理方式是使用setTimeout去假定异步的状态,这个处理方式是存在问题的,于是我在这篇文章的基础上做出了一些修改,通过在onopen事件和onerror事件中处理websocket未开启和正在开启状态的数据发送问题

目前使用到现在没有出现什么问题,复制即用

<template>
  <div class="test">

  </div></template><script>
  export default {    name : 'test',
    data() {      return {        websock: null,
      }
    },
    created() {      this.initWebSocket();
    },
    destroyed() {      this.websock.close() //离开路由之后断开websocket连接
    },    methods: {
      initWebSocket(){ //初始化weosocket
        const wsuri = "ws://127.0.0.1:8080";        this.websock = new WebSocket(wsuri);        this.websock.onmessage = this.websocketonmessage;        this.websock.onopen = this.websocketonopen;        this.websock.onerror = this.websocketonerror;        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        let actions = {"test":"12345"};        this.websocketsend(JSON.stringify(actions));
      },
      websocketonerror(){//连接建立失败重连
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
        const redata = JSON.parse(e.data);
      },
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
      },
    },
  }</script><style lang='less'>
 </style>



作者:Demo_Hu
链接:https://www.jianshu.com/p/9d8b2e42328c

點擊查看更多內容
5人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消