基于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函数用法

目录
相关文章
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
1394 139
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
742 1
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
1319 11
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
826 0
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
1294 1
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
927 17
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
690 0
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
414 0
|
JavaScript 前端开发 UED
Vue 项目中如何自定义实用的进度条组件
本文介绍了如何使用Vue.js创建一个灵活多样的自定义进度条组件。该组件可接受进度段数据数组作为输入,动态渲染进度段,支持动画效果和内容展示。当进度超出总长时,超出部分将以红色填充。文章详细描述了组件的设计目标、实现步骤(包括props定义、宽度计算、模板渲染、动画处理及超出部分的显示),并提供了使用示例。通过此组件,开发者可根据项目需求灵活展示进度情况,优化用户体验。资源地址:[https://pan.quark.cn/s/35324205c62b](https://pan.quark.cn/s/35324205c62b)。
721 0
|
JavaScript 前端开发 API
Vue 2 与 Vue 3 的区别:深度对比与迁移指南
Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,在过去的几年里,Vue 2 一直是前端开发中的重要工具。而 Vue 3 作为其升级版本,带来了许多显著的改进和新特性。在本文中,我们将深入比较 Vue 2 和 Vue 3 的主要区别,帮助开发者更好地理解这两个版本之间的变化,并提供迁移建议。 1. Vue 3 的新特性概述 Vue 3 引入了许多新特性,使得开发体验更加流畅、灵活。以下是 Vue 3 的一些关键改进: 1.1 Composition API Composition API 是 Vue 3 的核心新特性之一。它改变了 Vue 组件的代码结构,使得逻辑组
2521 0