亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

需求:

1.登錄成功后連接WebSocket

2.根據(jù)用戶id進行消息實時響應

3.有消息小紅點點亮,且需要進行聲音提示,反之

//icon+小紅點
<div class="relative right-menu-item hover-effect" @click="togglePopup">
    <el-icon class="dot el-icon-message-solid"> </el-icon>
    <!-- 如果有消息,顯示紅色圓點 -->
    <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('對應的文件路徑')"
       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/${需要響應數(shù)據(jù)的id}`);
// 將WebSocket實例保存到Vue的全局屬性中,以便在組件中訪問
Vue.prototype.$ws = ws;

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

created() {
    // 監(jiān)聽WebSocket消息
    this.$ws.onmessage = (message) => {
      let audio = document.getElementById("audio");
      audio.currentTime = 0; //從頭開始播放
      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;
      }
},

注意:

因為瀏覽器限制,可能會導致音頻無法播放

問題1:音頻可以播放,但是沒有聲音

處理:谷歌瀏覽器打開運行聲音播放

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

問題2:報錯 audioDom.play() 自動播放音頻時報錯:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

處理:強制給音頻除添加了點擊事件

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

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

      audio.currentTime = 0; //從頭開始播放
      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ǒng)發(fā)送通知

1.初始化websocket

此處存放于layout.vue中用于連接與斷開

mounted () {
    this.$websocket.initWebSocket()
  },
  destroyed () {
    // 離開路由之后斷開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ā)生錯誤' + 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有消息進行通知的文章就介紹到這了,更多相關(guān)vue2調(diào)用WebSocket消息通知內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論