基于Vue2+ElementUI/Vue3+ElementPlus对el-notification增加倒计时进度条特效,鼠标移入,暂停计时,鼠标移出,继续计时

简介: 本文介绍了如何在Vue2+ElementUI和Vue3+ElementPlus项目中对`el-notification`组件增加倒计时进度条特效,并实现鼠标移入通知时暂停计时,鼠标移出时继续计时的功能。

前言

遇到一个需求就是对这个 el-notification 加一个倒计时进度条,方便用户知道该通知何时自动关闭。于是自己动手丰衣足食。

一、示例代码

(1)基于Vue2+ElementUI的项目

<template>
  <div>
    <el-button @click="showTip">do it</el-button>
  </div>
</template>

<script>
export default {
   
   
  data: () => ({
   
   

  }),
  created() {
   
   
    console.log('created =>', 'SUCCESS')

    // 在 created 生命周期,调用 method 的 yyyyyy 方法
    // this.yyyyyy();
  },
  methods: {
   
   
    /**
     * 通知消息
     */
    showTip() {
   
   
      const h = this.$createElement;
      const contents = []
      const msg = h('p', {
   
   }, '任务启动成功!')
      const task = h('p', {
   
   }, '任务ID:' + 1234)
      const job = h('p', {
   
   }, 'JobID:' + 661234)
      const progress = h(
        'div',
        {
   
   
          class: {
   
   
            'el-progress-plus': true
          },
          style: {
   
   
              'width': '230px',
              'height': '6px',
              'background-color': '#5e7ce0',
              'margin-top': '6px',
              'border-radius': '6px',
          },
          percentage: 100
        },
        ''
      )
      const br = h('p', {
   
    style: 'width: auto; height: 10px' }, '')
      contents.push(msg)
      contents.push(task)
      contents.push(job)
      contents.push(progress)
      contents.push(br)

      let classID = 1
      let className = 'el-notification-plus' + classID
      // 判断是否已存在该通知元素,以及最多限制生成10000个通知
      while(document.getElementsByClassName(className)[0]) {
   
   
        if (classID > 10000) {
   
   
          // 无法生成元素
          console.log('无法生成元素')
          break
        } else {
   
   
          // 继续累加
          classID++
          className = 'el-notification-plus' + classID
        }
      }

      // 实例化通知
      const notifyInstance = this.$notify({
   
   
        title: '一键测试',
        type: 'success',
        customClass: className,
        message: h('div', {
   
   }, contents),
        duration: 0
      })

      // 启动倒计时
      let timer = this.countDown(className, notifyInstance)

      // 获取 Notification 的DOM元素
      const ElNotificationPlus = document.getElementsByClassName(className)[0]
      // console.log('ElNotificationPlus =>', ElNotificationPlus)

      // 为 Notification 元素 定义鼠标进入方法,暂停倒计时
      ElNotificationPlus.onmouseenter = () => {
   
   
        console.log('onmouseover~', className)
        clearInterval(timer)
      }

      // 为 Notification 元素 定义鼠标移出方法,继续倒计时
      ElNotificationPlus.onmouseleave = () => {
   
   
        console.log('onmouseout~', className)
        clearInterval(timer)
        timer = this.countDown(className, notifyInstance)
      }
    },

    /**
     * 倒计时
     */
    countDown(className, notifyInstance) {
   
   
      const timer = setInterval(() => {
   
   
        try {
   
   
          if (notifyInstance) {
   
   
            const ElNotificationPlus = document.getElementsByClassName(className)[0]
            // console.log('ElNotificationPlus =>', ElNotificationPlus)
            const ElProgressPlus = ElNotificationPlus.getElementsByClassName('el-progress-plus')[0]
            // console.log('ElProgressPlus =>', ElProgressPlus)

            let percentage = ElProgressPlus.getAttribute('percentage')
            if (percentage >= 0) {
   
   
              percentage = percentage - 0.5
              ElProgressPlus.setAttribute('percentage', percentage)
              ElProgressPlus.style.width = (230 * (percentage / 100)) + 'px'
            } else {
   
   
              // 清除定时器
              clearInterval(timer)

              // 手动关闭通知
              setTimeout(() => {
   
   
                notifyInstance.close()
              }, 50);
            }
          } else {
   
   
            // 清除定时器
            clearInterval(timer)
          }
        } catch (error) {
   
   
          // 清除定时器
          clearInterval(timer)
        }
      }, 50)

      return timer
    },
  }
}
</script>

<style>
  .el-notification-plus .el-progress .el-progress__text{
   
   
    display: none;
  }
</style>

(1)基于Vue3+ElementPlus的项目

<template>
  <div>
    <el-button @click="showTip">do it</el-button>
  </div>
</template>

<script>
import {
   
    h, onMounted, getCurrentInstance } from 'vue'

export default {
   
   
  setup() {
   
   
    onMounted(() => {
   
   
      console.log('onMounted =>', 'SUCCESS')

      // const { proxy  } = getCurrentInstance()

      // 在 onMounted 生命周期,调用 method 的 xxxxxx 方法
      // proxy.xxxxxx()
    })
  },
  data: () => ({
   
   

  }),
  created() {
   
   
    console.log('created =>', 'SUCCESS')

    // 在 created 生命周期,调用 method 的 yyyyyy 方法
    // this.yyyyyy();
  },
  methods: {
   
   
    /**
     * 通知消息
     */
    showTip() {
   
   
      const contents = []
      const msg = h('p', {
   
   }, '任务启动成功!')
      const task = h('p', {
   
   }, '任务ID:' + 1234)
      const job = h('p', {
   
   }, 'JobID:' + 661234)
      const progress = h(
        'div',
        {
   
   
          class: {
   
   
            'el-progress-plus': true
          },
          style: {
   
   
              'width': '230px',
              'height': '6px',
              'background-color': '#5e7ce0',
              'margin-top': '6px',
              'border-radius': '6px',
          },
          percentage: 100
        },
        ''
      )
      const br = h('p', {
   
    style: 'width: auto; height: 10px' }, '')
      contents.push(msg)
      contents.push(task)
      contents.push(job)
      contents.push(progress)
      contents.push(br)

      let classID = 1
      let className = 'el-notification-plus' + classID
      // 判断是否已存在该通知元素,以及最多限制生成100个通知
      while(document.getElementsByClassName(className)[0]) {
   
   
        if (classID > 100) {
   
   
          // 无法生成元素
          console.log('无法生成元素')
          break
        } else {
   
   
          // 继续累加
          classID++
          className = 'el-notification-plus' + classID
        }
      }

      // 实例化通知
      const notifyInstance = this.$notify({
   
   
        title: '一键测试',
        type: 'success',
        customClass: className,
        message: h('div', {
   
   }, contents),
        duration: 0
      })

      // 启动倒计时
      let timer = this.countDown(className, notifyInstance)

      // 获取 Notification 的DOM元素
      const ElNotificationPlus = document.getElementsByClassName(className)[0]
      // console.log('ElNotificationPlus =>', ElNotificationPlus)

      // 为 Notification 元素 定义鼠标进入方法,暂停倒计时
      ElNotificationPlus.onmouseenter = () => {
   
   
        console.log('onmouseover~', className)
        clearInterval(timer)
      }

      // 为 Notification 元素 定义鼠标移出方法,继续倒计时
      ElNotificationPlus.onmouseleave = () => {
   
   
        console.log('onmouseout~', className)
        clearInterval(timer)
        timer = this.countDown(className, notifyInstance)
      }
    },

    /**
     * 倒计时
     */
    countDown(className, notifyInstance) {
   
   
      const timer = setInterval(() => {
   
   
        try {
   
   
          if (notifyInstance) {
   
   
            const ElNotificationPlus = document.getElementsByClassName(className)[0]
            // console.log('ElNotificationPlus =>', ElNotificationPlus)
            const ElProgressPlus = ElNotificationPlus.getElementsByClassName('el-progress-plus')[0]
            // console.log('ElProgressPlus =>', ElProgressPlus)

            let percentage = ElProgressPlus.getAttribute('percentage')
            if (percentage >= 0) {
   
   
              percentage = percentage - 0.5
              ElProgressPlus.setAttribute('percentage', percentage)
              ElProgressPlus.style.width = (230 * (percentage / 100)) + 'px'
            } else {
   
   
              // 清除定时器
              clearInterval(timer)

              // 手动关闭通知
              setTimeout(() => {
   
   
                notifyInstance.close()
              }, 50);
            }
          } else {
   
   
            // 清除定时器
            clearInterval(timer)
          }
        } catch (error) {
   
   
          // 清除定时器
          clearInterval(timer)
        }
      }, 50)

      return timer
    },
  }
}
</script>

<style>
  .el-notification-plus .el-progress .el-progress__text{
   
   
    display: none;
  }
</style>

二、运行效果

三、参考资料

JS DOM获取元素属性+操作方法
Vue2的h函数(createElement)与Vue3中的h函数用法

目录
相关文章
|
10月前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
627 1
|
10月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
1211 139
|
10月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
695 0
|
11月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
1103 11
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
1139 1
|
10月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
682 137
|
11月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
808 2
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
608 0
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
865 1
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
1481 0