<template> <div> <button @click="send">发消息</button> </div> </template> <script> export default { data () { return { path: 'ws://192.168.1.177:17750/imserver/', socket: '' } }, computed:{ userId(){ let userId = this.$store.getters.id; return userId } }, watch(){ //监听userid,获取到了再执行websocket连接 userId(){ // 初始化 this.init() } }, methods: { init() { if(typeof(WebSocket) === "undefined"){ alert("您的浏览器不支持socket") }else{ if(!this.userId){ alert('用户ID获取失败导致WebSocket连接失败!'); }else{ const path = this.path + this.userId; // 实例化socket this.socket = new WebSocket(path) // 监听socket连接 this.socket.onopen = this.open // 监听socket错误信息 this.socket.onerror = this.error // 监听socket消息 this.socket.onmessage = this.getMessage // 监听socket关闭 this.socket.onclose = this.close; } } }, open() { console.log('socket连接成功') }, error() { console.log('连接错误') }, getMessage(msg) { console.log('收到消息',msg); }, send() { this.socket.send() }, close() { console.log("socket已经关闭") } }, // 销毁监听 destroyed(){ if(this.socket){ this.socket.close(); } } } </script>
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!