VUE WebSocket的使用

直接附上代码:

created(){

    this.initWebSocket();

},

destroyed() {

    this.websock.close();//离开路由之后断开websocket连接

},

initWebSocket(){//初始化weosocket(必须)

const url = "ws://请求的接口地址";    //请根据实际项目需要进行修改

this.websock = new WebSocket(url);      //新建一个webstock对象

this.websock.onmessage = this.websocketonmessage;  

this.websock.onopen = this.websocketonopen;      

this.websock.onerror = this.websocketonerror;

this.websock.onclose = this.websocketclose;

},

websocketonopen(){//websocket连接后发送数据(send发送)

    console.log('websocket创建成功')

},

websocketonmessage(e){ //数据接收

    var message = JSON.parse(event.data); // 这里是关键 JSON.parse 必须写上,不然拿不到数据

},

websocketonerror(){//连接建立失败重连

    this.initWebSocket();

},

websocketclose(e){  //关闭

    console.log('断开连接',e);

}

刚开始测试的时候,可以让后端手动传一条数据给你,前端测试一下。

最后你会发现 更新数据的时候 就会接收到websocket的数据,这样就成功了 (后面就是动态的替换数据和插入数据了)。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容