vue通知提醒消息

目录

前言

一、Notification

二、Notification引用

           1.全局引用

           2.单独引用

三、参数说明

四、简单案例 

五、项目实战

1、定义全局Notification。

2、Websocket实时接收通知。

3、消息通知



前言

最近有个项目需求就是在客户端的右上角要实时展示提醒消息,下面来看下简单的实现步骤


一、Notification

这是基于悬浮出现在页面角落,显示全局的通知提醒消息。这个elmennt-ui组件可以实现我们上面的功能。

二、Notification引用

1.全局引用

element 为 Vue.prototype 添加了全局方法 $notify。因此在 vue instance 中可以采用本页面中的方式调用 Notification。

2.单独引用

import { Notification } from 'element-ui';

此时调用方法为 Notification(options)。我们也为每个 type 定义了各自的方法,如 Notification.success(options)。并且可以调用 Notification.closeAll() 手动关闭所有实例。

三、参数说明


四、简单案例 

右上角就会弹出我们写的html代码段是不是特别简单

<template>
  <el-button
    plain
    @click="open">
    使用 HTML 片段
  </el-button>
</template>

<script>
  export default {
    methods: {
      open() {
        this.$notify({
          title: 'HTML 片段',
          dangerouslyUseHTMLString: true,
          message: '<strong>这是 <i>HTML</i> 片段</strong>'
        });
      }
    }
  }
</script>

五、项目实战

这里大概说一下我的流程,我这里需要建立Websocket连接,服务器实时推送信息给客户端在右上角展示,这里需要用到Websocket以及本章学的通知。Websocket在前一章有讲。案例仅供参考。

1、定义全局Notification。

/* 全局Notification */
	Vue.prototype.$baseNotify = (message, title, type, position) => {
		Notification({
			title: title,
			message: message,
			position: position || 'top-right',
			type: type || 'success',
			duration: messageDuration,
		})
	}

2、Websocket实时接收通知。

initWebSocket() {
        const token = getAccessToken()

        const wsurl = `${this.troubelUrl}?code=trouble&token=${token}`
        this.twebsock = new WebSocket(wsurl)
        this.twebsock.onmessage = this.websocketonmessage
        this.twebsock.onopen = this.websocketonopen
        this.twebsock.onerror = this.websocketonerror
        this.twebsock.onclose = this.websocketclose
      },
      websocketonopen() {
        //webscoket定时心跳
        this.troubleTimer = setInterval(() => {
          let pageUrl = window.location.hash
          if (pageUrl !== '' && pageUrl !== '#/login') {
            this.websocketsend('heartbeat')
          }
        }, 50000)
        console.log('数据发送...')
      },
      websocketonerror(e) {
        //连接建立失败重连
        setTimeout(() => {
          this.initWebSocket()
        }, 10000)
        console.log('故障连接出错~')
      },
      websocketonmessage(evt) {
        var monitorData = evt.data
        monitorData = JSON.parse(monitorData)
        this.switchOther(this.troublePush, monitorData)
      },
      //根据数据判断进行弹框(紧急呼叫,长时间关人)
      switchOther(switchValue, monitorData) {
        if (switchValue === true || switchValue === 'true') {
            this.handleOpen(monitorData)
        }
      },
      websocketsend(data) {
        this.twebsock.send(data)
      },
      websocketclose(e) {
        if (this.twebsock == null) {
          return
        }
        this.twebsock.close()
        this.twebsock = null
        clearInterval(this.troubleTimer)
        console.log('故障推送关闭~')
      },

3、消息通知

      //monitorItem取的前面Websocket返回回来的值
      handleOpen(monitorItem) {
        this.openDialogflase = true
        const h = this.$createElement
        let notify = this.$notify({
          title: monitorItem.troubleType,
          message: h('p', null, [
            h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  margin: '0 0 10px 0',
                },
              },
              `${monitorItem.projectName}-${monitorItem.useCode}`
            ),
            h(
              'p',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  margin: '0 0 5px 0',
                },
              },
              [
                h('span', null, monitorItem.duration),
                h(
                  'span',
                  {
                    style: {
                      color: '#efefef',
                    },
                  },
                  monitorItem.fromType
                ),
              ]
            ),
            h('p', null, monitorItem.address),
            h(
              'button',
              {
                style: {
                  padding: '5px 20px',
                  fontSize: '14px',
                  borderRadius: '4px',
                  color: '#fff',
                  background: '#ff575a',
                  border: 'none',
                  margin: '10px 10px 0 0',
                  display: 'inline-block',
                },
                on: {
                  click: this.clickBtn.bind(this, monitorItem),
                },
              },
              '查看详情'
            ),
            h(
              'button',
              {
                style: {
                  padding: '5px 20px',
                  fontSize: '14px',
                  borderRadius: '4px',
                  color: '#fff',
                  background: '#ff575a',
                  border: 'none',
                  margin: '10px 10px 0 0',
                  display: 'inline-block',
                },
                on: {
                  click: this.handleShi.bind(this, monitorItem),
                },
              },
              '双向视频'
            ),
            h(
              'button',
              {
                style: {
                  padding: '5px 20px',
                  fontSize: '14px',
                  borderRadius: '4px',
                  color: '#fff',
                  background: '#ff575a',
                  border: 'none',
                  margin: '10px 0 0 0',
                  display: 'inline-block',
                },
                on: {
                  click: this.handleQuXiao.bind(this, monitorItem),
                },
              },
              '取消'
            ),
          ]),
          duration: 0,
          showClose: false,
        })

        //将通知实例放入       
 this.notifications[monitorItem.orderKey] = notify
        this.handleAudio()
      },
 //关闭当前故障弹框
      handleQuXiao(monitorItem) {
        this.openDialogflase = false
        this.notifications[monitorItem.orderKey].close()
        delete this.notifications[monitorItem.orderKey]
      },
      //关闭所有弹窗
      closeAll() {
        let vue = this
        for (let key in vue.notifications) {
          vue.notifications[key].close()
          delete vue.notifications[key]
        }
      },
  • 5
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现消息通知,可以借助Vue、ElementUI和Websockets,以下是基本的实现步骤: 1. 安装Vue和ElementUI 使用命令行工具,进入项目目录,执行以下命令: ``` npm install vue npm install element-ui ``` 2. 引入ElementUI组件 在Vue的入口文件中,引入需要使用的ElementUI组件,例如Notification、MessageBox等。 ``` import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) ``` 3. 创建WebSocket连接 在Vue组件中通过Websockets连接后端服务器,建立WebSocket连接,接收服务器推送消息。 ``` // 建立WebSocket连接 const webSocket = new WebSocket('ws://localhost:8080') // 监听WebSocket连接打开事件 webSocket.onopen = function () { console.log('WebSocket连接已打开') } // 监听WebSocket接收到消息事件 webSocket.onmessage = function (event) { console.log('WebSocket接收到消息:' + event.data) // 处理接收到的消息 } // 监听WebSocket连接关闭事件 webSocket.onclose = function () { console.log('WebSocket连接已关闭') } ``` 4. 处理接收到的消息 在WebSocket监听到有消息时,可以使用ElementUI的Notification组件弹出通知框,提醒用户有新消息。 ``` // 处理WebSocket接收到的消息 webSocket.onmessage = function (event) { console.log('WebSocket接收到消息:' + event.data) // 弹出通知框 const msg = JSON.parse(event.data) Notification({ title: '新消息', message: msg.content }) // 弹出确认框 MessageBox.confirm(msg.content, '新消息', { confirmButtonText: '查看详情', cancelButtonText: '忽略', type: 'info' }).then(() => { // 用户点击了查看详情按钮 // 处理跳转逻辑 }).catch(() => { // 用户点击了忽略按钮 // 不做任何处理 }) } ``` 以上就是使用Vue、ElementUI和Websockets实现消息通知的基本步骤。需要注意的是,WebSocket连接的建立和关闭需要在组件的mounted和beforeDestroy生命周期函数中分别进行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

混世大魔王955

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值