Vue开发websocket通讯即时通信消息通知
<template> <div class="app-wrapper"> <div class="message" v-show="hasMes"> <div class="header"><i class="el-icon-close" style="float: right;cursor: pointer;color: white;line-height: 1.4;" @click="hideMessage"></i></div> <div class="content"><span>{{content}}</span></div> </div> </div> </template> <script> export default { name: 'Layout', components: { }, data() { return { hasMes:false, content:'', } }, methods: { hideMessage() { this.hasMes = false; this.content = ''; }, initWebSocket () { // 连接错误 this.websocket.onerror = this.setErrorMessage // 连接成功 this.websocket.onopen = this.setOnopenMessage // 收到消息的回调 this.websocket.onmessage = this.setOnmessageMessage // 连接关闭的回调 this.websocket.onclose = this.setOncloseMessage // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = this.onbeforeunload }, setErrorMessage () { this.initWebSocket(); }, setOnopenMessage () { }, setOnmessageMessage (event) { // 根据服务器推送的消息做自己的业务处理 this.hasMes = true; let messageData = JSON.parse(event.data); this.content = messageData.content; setTimeout(() => { this.hasMes = false; }, 5 * 1000) }, setOncloseMessage () { }, onbeforeunload () { this.closeWebSocket() }, closeWebSocket () { this.websocket.close() } }, created() { if ('WebSocket' in window) { const wsuri = "ws://" + location.host + "/websocket/admin"; //路径可根据不同用户指定,此处我指定的是用户名 this.websocket = new WebSocket(wsuri); this.initWebSocket() } else { alert('当前浏览器 Not support websocket') } }, mounted(){ }, destroyed() { this.websock.close() //离开路由之后断开websocket连接 }, } </script> <style lang="scss" scoped> .message{ position: absolute; bottom: 20px; right: 50px; width: 300px; height: 100px; background: #fff; border: 1px solid #7289ac; border-radius: 5px; } .message .header{ width: 100%; height: 23px; background: #7289ac; } .message .content{ width: 100%; height: 80px; border: none; padding: 20px 10px 10px 10px; } .app-wrapper { @include clearfix; position: relative; height: 100%; width: 100%; } </style>