1. 程式人生 > 其它 >Vue開發websocket通訊即時通訊訊息通知

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>