欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue2前端調(diào)用WebSocket有消息進(jìn)行通知代碼示例

 更新時(shí)間:2024年07月26日 16:47:15   作者:lili@  
在Vue項(xiàng)目中實(shí)現(xiàn)全局的消息鏈接監(jiān)聽(tīng)主要涉及到了WebSocket技術(shù),這是一種雙向通信協(xié)議,允許客戶(hù)端與服務(wù)器之間實(shí)時(shí)、高效地交換數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于vue2前端調(diào)用WebSocket有消息進(jìn)行通知的相關(guān)資料,需要的朋友可以參考下

需求:

1.登錄成功后連接WebSocket

2.根據(jù)用戶(hù)id進(jìn)行消息實(shí)時(shí)響應(yīng)

3.有消息小紅點(diǎn)點(diǎn)亮,且需要進(jìn)行聲音提示,反之

//icon+小紅點(diǎn)
<div class="relative right-menu-item hover-effect" @click="togglePopup">
    <el-icon class="dot el-icon-message-solid"> </el-icon>
    <!-- 如果有消息,顯示紅色圓點(diǎn) -->
    <span v-if="hasMessage" class="red-dot"></span>
    <!-- 彈窗內(nèi)容,根據(jù)需要顯示和隱藏 -->
    <el-dialog title="審核通知" :visible.sync="showPopup" append-to-body>
        <p>
           {{ messageContent }}
        </p>
    </el-dialog>
</div>

//音頻
<div id="wrap">
    <p>
      <audio
       :src="require('對(duì)應(yīng)的文件路徑')"
       id="audio"
       preload="auto"
       muted
       type="audio/mp3"
       controls="controls"
      ></audio>
    </p>
</div>

css樣式
.dot {
  position: absolute;
  top: 14px;
  right: 190px;
  font-size: 20px;
}

.red-dot {
  position: absolute;
  top: 14px;
  right: 190px;
  height: 10px;
  width: 10px;
  background-color: red;
  border-radius: 50%;
  z-index: 999;
}

#wrap {
  display: none;
}
// 登錄成功調(diào)用WebSocket
const ws = new WebSocket(`ws://后端域名/websocket/${需要響應(yīng)數(shù)據(jù)的id}`);
// 將WebSocket實(shí)例保存到Vue的全局屬性中,以便在組件中訪問(wèn)
Vue.prototype.$ws = ws;

data() {
    return {
      hasMessage: false,
      showPopup: false,
      messageContent: "",
    };
},

created() {
    // 監(jiān)聽(tīng)WebSocket消息
    this.$ws.onmessage = (message) => {
      let audio = document.getElementById("audio");
      audio.currentTime = 0; //從頭開(kāi)始播放
      audio.muted = false; //取消靜音
      audio.play().then(() => {
        // 播放成功
        console.log('音頻播放成功');
      }).catch((error) => {
        // 播放失敗
        console.error('音頻播放失敗', error);
      });

      // 改變鈴鐺狀態(tài)
      this.hasMessage = true;
      this.messageContent = message.data;
    };
},

togglePopup() {
    if (this.messageContent != "") {
        this.showPopup = true;
      }
},

注意:

因?yàn)闉g覽器限制,可能會(huì)導(dǎo)致音頻無(wú)法播放

問(wèn)題1:音頻可以播放,但是沒(méi)有聲音

處理:谷歌瀏覽器打開(kāi)運(yùn)行聲音播放

網(wǎng)站設(shè)置,將通知和聲音改成允許

問(wèn)題2:報(bào)錯(cuò) audioDom.play() 自動(dòng)播放音頻時(shí)報(bào)錯(cuò):Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

處理:強(qiáng)制給音頻除添加了點(diǎn)擊事件

created() {
    // 監(jiān)聽(tīng)WebSocket消息
    this.$ws.onmessage = (message) => {
      let audio = document.getElementById("audio");

       //強(qiáng)制添加點(diǎn)擊事件
      let playButton = document.getElementById("wrap");
      var event = new MouseEvent("click", {
        bubbles: true,
        cancelable: true,
        view: window,
      });
      playButton.dispatchEvent(event);

      audio.currentTime = 0; //從頭開(kāi)始播放
      audio.muted = false; //取消靜音
      audio.play().then(() => {
        // 播放成功
        console.log('音頻播放成功');
      }).catch((error) => {
        // 播放失敗
        console.error('音頻播放失敗', error);
      });

      // 改變鈴鐺狀態(tài)
      this.hasMessage = true;
      this.messageContent = message.data;
    };
},

附:vue2中使用websocket用于后臺(tái)管理系統(tǒng)發(fā)送通知

1.初始化websocket

此處存放于layout.vue中用于連接與斷開(kāi)

mounted () {
    this.$websocket.initWebSocket()
  },
  destroyed () {
    // 離開(kāi)路由之后斷開(kāi)websocket連接
    this.$websocket.closeWebsocket()
  }

2.websocket.js

import ElementUI from 'element-ui'
import util from '@/libs/util'
import store from '@/store'
function initWebSocket (e) {
  const token = util.cookies.get('token')
  if (token) {
    const wsUri = util.wsBaseURL() + 'ws/' + token + '/'
    this.socket = new WebSocket(wsUri)// 這里面的this都指向vue
    this.socket.onerror = webSocketOnError
    this.socket.onmessage = webSocketOnMessage
    this.socket.onclose = closeWebsocket
  }
}
function webSocketOnError (e) {
  ElementUI.Notification({
    title: '',
    message: 'WebSocket連接發(fā)生錯(cuò)誤' + JSON.stringify(e),
    type: 'error',
    position: 'bottom-right',
    duration: 3000
  })
}
/**
 * 接收消息
 * @param e
 * @returns {any}
 */
function webSocketOnMessage (e) {
  const data = JSON.parse(e.data)
  const { refreshUnread, systemConfig } = data
  if (refreshUnread) {
    // 更新消息通知條數(shù)
    store.dispatch('admin/messagecenter/setUnread')
  }
  if (systemConfig) {
    // 更新系統(tǒng)配置
    this.$store.dispatch('admin/settings/load')
  }
  if (data.contentType === 'SYSTEM') {
    ElementUI.Notification({
      title: '系統(tǒng)消息',
      message: data.content,
      type: 'success',
      position: 'bottom-right',
      duration: 3000
    })
  } else if (data.contentType === 'ERROR') {
    ElementUI.Notification({
      title: '',
      message: data.content,
      type: 'error',
      position: 'bottom-right',
      duration: 0
    })
  } else if (data.contentType === 'INFO') {
    ElementUI.Notification({
      title: '溫馨提示',
      message: data.content,
      type: 'success',
      position: 'bottom-right',
      duration: 0
    })
  } else {
    ElementUI.Notification({
      title: '溫馨提示',
      message: data.content,
      type: 'info',
      position: 'bottom-right',
      duration: 3000
    })
  }
}
// 關(guān)閉websiocket
function closeWebsocket () {
  console.log('連接已關(guān)閉...')
  ElementUI.Notification({
    title: 'websocket',
    message: '連接已關(guān)閉...',
    type: 'danger',
    position: 'bottom-right',
    duration: 3000
  })
}
/**
 * 發(fā)送消息
 * @param message
 */
function webSocketSend (message) {
  this.socket.send(JSON.stringify(message))
}
export default {
  initWebSocket, closeWebsocket, webSocketSend
}

總結(jié) 

到此這篇關(guān)于vue2前端調(diào)用WebSocket有消息進(jìn)行通知的文章就介紹到這了,更多相關(guān)vue2調(diào)用WebSocket消息通知內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論