vue2前端调用WebSocket有消息进行通知代码示例

 更新时间:2024年07月26日 16:47:15   作者:lili@  
在Vue项目中实现全局的消息链接监听主要涉及到了WebSocket技术,这是一种双向通信协议,允许客户端与服务器之间实时、高效地交换数据,这篇文章主要给大家介绍了关于vue2前端调用WebSocket有消息进行通知的相关资料,需要的朋友可以参考下

需求:

1.登录成功后连接WebSocket

2.根据用户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>
    <!-- 弹窗内容,根据需要显示和隐藏 -->
    <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;
}
// 登录成功调用WebSocket
const ws = new WebSocket(`ws://后端域名/websocket/${需要响应数据的id}`);
// 将WebSocket实例保存到Vue的全局属性中,以便在组件中访问
Vue.prototype.$ws = ws;

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

created() {
    // 监听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);
      });

      // 改变铃铛状态
      this.hasMessage = true;
      this.messageContent = message.data;
    };
},

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

注意:

因为浏览器限制,可能会导致音频无法播放

问题1:音频可以播放,但是没有声音

处理:谷歌浏览器打开运行声音播放

网站设置,将通知和声音改成允许

问题2:报错 audioDom.play() 自动播放音频时报错:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

处理:强制给音频除添加了点击事件

created() {
    // 监听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);
      });

      // 改变铃铛状态
      this.hasMessage = true;
      this.messageContent = message.data;
    };
},

附:vue2中使用websocket用于后台管理系统发送通知

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连接发生错误' + 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) {
    // 更新消息通知条数
    store.dispatch('admin/messagecenter/setUnread')
  }
  if (systemConfig) {
    // 更新系统配置
    this.$store.dispatch('admin/settings/load')
  }
  if (data.contentType === 'SYSTEM') {
    ElementUI.Notification({
      title: '系统消息',
      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
    })
  }
}
// 关闭websiocket
function closeWebsocket () {
  console.log('连接已关闭...')
  ElementUI.Notification({
    title: 'websocket',
    message: '连接已关闭...',
    type: 'danger',
    position: 'bottom-right',
    duration: 3000
  })
}
/**
 * 发送消息
 * @param message
 */
function webSocketSend (message) {
  this.socket.send(JSON.stringify(message))
}
export default {
  initWebSocket, closeWebsocket, webSocketSend
}

总结 

到此这篇关于vue2前端调用WebSocket有消息进行通知的文章就介绍到这了,更多相关vue2调用WebSocket消息通知内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vue状态管理库Pinia详细介绍

    Vue状态管理库Pinia详细介绍

    这篇文章主要介绍了Vue3-pinia状态管理,pinia是 vue3 新的状态管理工具,简单来说相当于之前 vuex,它去掉了 Mutations 但是也是支持 vue2 的,需要的朋友可以参考下
    2022-08-08
  • 如何在Vue项目中添加接口监听遮罩

    如何在Vue项目中添加接口监听遮罩

    这篇文章主要介绍了如何在Vue项目中添加接口监听遮罩,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • vue.js云存储实现图片上传功能

    vue.js云存储实现图片上传功能

    示对象存储是腾讯云提供的一种存储海量文件的分布式存储服务,本文主要介绍了用vue.js实现图片上传功能,感兴趣的小伙伴们可以参考一下
    2021-05-05
  • vue使用axios导出后台返回的文件流为excel表格详解

    vue使用axios导出后台返回的文件流为excel表格详解

    这篇文章主要介绍了vue使用axios导出后台返回的文件流为excel表格方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • vue2.6.10+vite2开启template模板动态编译的过程

    vue2.6.10+vite2开启template模板动态编译的过程

    这篇文章主要介绍了vue2.6.10+vite2开启template模板动态编译,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-02-02
  • 详解关于Vuex的action传入多个参数的问题

    详解关于Vuex的action传入多个参数的问题

    这篇文章主要介绍了详解关于Vuex的action传入多个参数的问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-02-02
  • 详解Vue返回值动态生成表单及提交数据的办法

    详解Vue返回值动态生成表单及提交数据的办法

    这篇文章主要为大家介绍了Vue返回值动态生成表单及提交数据,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-12-12
  • windows下vue.js开发环境搭建教程

    windows下vue.js开发环境搭建教程

    这篇文章主要为大家详细介绍了windows下vue.js开发环境搭建教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-03-03
  • vue根据权限动态渲染按钮、组件等的函数式组件实现

    vue根据权限动态渲染按钮、组件等的函数式组件实现

    这篇文章主要介绍了vue根据权限动态渲染按钮、组件等的函数式组件实现方式,具有很好的参考价值,希望杜大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • vue cli使用绝对路径引用图片问题的解决

    vue cli使用绝对路径引用图片问题的解决

    这篇文章主要给大家介绍了关于vue cli使用绝对路径引用图片问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起看看吧。
    2017-12-12

最新评论