el-notification详解

312 阅读2分钟

el-notificationElement Plus 框架中的通知组件,用于在页面顶部或底部显示提示信息。它可以用于显示成功、警告、错误等不同类型的通知。

el-notification 方法详解

el-notification 主要通过静态方法调用,而不是作为一个组件直接使用。以下是常用的方法及其参数:

  1. ElNotification(options) :

    • 用途: 显示一个通知。

    • 参数:

      • options: 配置选项。

el-notification 配置选项详解

  1. title:

    • 类型: String
    • 用途: 通知标题。
    • 默认值: 
  2. message:

    • 类型: String | VNode
    • 用途: 通知内容。
    • 默认值: 
  3. type:

    • 类型: String
    • 用途: 通知类型,可选值为 successwarninginfoerror
    • 默认值: info
  4. duration:

    • 类型: Number
    • 用途: 通知显示的时间(毫秒),设置为 0 表示不会自动关闭。
    • 默认值: 3000
  5. position:

    • 类型: String
    • 用途: 通知显示的位置,可选值为 top-righttop-leftbottom-rightbottom-left
    • 默认值: top-right
  6. showClose:

    • 类型: Boolean
    • 用途: 是否显示关闭按钮。
    • 默认值: true
  7. onClose:

    • 类型: Function
    • 用途: 关闭通知时的回调函数。
    • 默认值: 
  8. offset:

    • 类型: Number
    • 用途: 通知距离顶部或底部的距离。
    • 默认值: 0
  9. customClass:

    • 类型: String
    • 用途: 自定义通知的类名。
    • 默认值: 
  10. iconClass:

    • 类型: String
    • 用途: 自定义通知图标的类名。
    • 默认值: 

完整示例代码

<template>
  <div>
    <h2>Notification 示例</h2>

    <!-- 成功通知 -->
    <el-button @click="showSuccess">显示成功通知</el-button>

    <!-- 警告通知 -->
    <el-button @click="showWarning">显示警告通知</el-button>

    <!-- 错误通知 -->
    <el-button @click="showError">显示错误通知</el-button>

    <!-- 自定义通知 -->
    <el-button @click="showCustom">显示自定义通知</el-button>
  </div>
</template>

<script setup>
import { ElNotification } from 'element-plus'

const showSuccess = () => {
  ElNotification({
    title: '成功',
    message: '这是一个成功的通知',
    type: 'success',
    duration: 2000
  })
}

const showWarning = () => {
  ElNotification({
    title: '警告',
    message: '这是一个警告的通知',
    type: 'warning',
    duration: 3000
  })
}

const showError = () => {
  ElNotification({
    title: '错误',
    message: '这是一个错误的通知',
    type: 'error',
    duration: 4000
  })
}

const showCustom = () => {
  ElNotification({
    title: '自定义',
    message: '这是一个自定义的通知',
    type: 'info',
    duration: 0, // 不会自动关闭
    position: 'bottom-right',
    showClose: true,
    onClose: () => {
      console.log('通知已关闭')
    },
    customClass: 'custom-notification',
    iconClass: 'el-icon-warning'
  })
}
</script>

代码解释

  1. 成功通知:

    • 使用 ElNotification 方法显示一个成功通知,并设置标题、内容、类型和显示时间。
    • <el-button @click="showSuccess">显示成功通知</el-button>
      
  2. 警告通知:

    • 使用 ElNotification 方法显示一个警告通知,并设置标题、内容、类型和显示时间。
    • <el-button @click="showWarning">显示警告通知</el-button>
      
  3. 错误通知:

    • 使用 ElNotification 方法显示一个错误通知,并设置标题、内容、类型和显示时间。
    • <el-button @click="showError">显示错误通知</el-button>
      
  4. 自定义通知:

    • 使用 ElNotification 方法显示一个自定义通知,并设置标题、内容、类型、显示时间、位置、是否显示关闭按钮、关闭时的回调函数、自定义类名和图标类名。
    • <el-button @click="showCustom">显示自定义通知</el-button>