<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>
vue项目中使用websocket
我爱模板网做一个项目,A用户发了消息给B用户,B用户要能实时收到,明显的,需要用到WebSocket。下面是我爱模板网用在vue项目中的WebSocket代码: