[Element Plus 源码解析] Alert 警告

1,563 阅读1分钟

一、组件介绍

Alert组件用于页面中展示重要的提示信息,是页面中的非浮层元素,不会自动消失。详细可参看:[官网链接](组件 | Element (gitee.io))

1.1 属性

  • title:标题,也可以通过title插槽自定义标题;
  • type: 类型,有success/warning/info/error四种类型,默认是info;
  • description:辅助性描述信息,也可通过默认插槽自定义内容;
  • closable:是否显示关闭按钮
  • close-text: 关闭按钮自定义文本
  • show-icon:是否显示图标
  • center: 文字是否居中
  • effect: 主题,有两种:light/dark,默认为ligth

1.2 事件

  • close: 关闭alert时触发

二、源码分析

2.1 template

<template>
  // vue官方过渡组件,提供过渡效果 
  <transition name="el-alert-fade">
    // v-show 控制显示隐藏
    <div
      v-show="visible"
      class="el-alert"
      :class="[typeClass, center ? 'is-center' : '', 'is-' + effect]"
      role="alert"
    >
      <i v-if="showIcon" class="el-alert__icon" :class="[ iconClass, isBigIcon ]"></i>
      <div class="el-alert__content">
         // title部分,提供具名插槽
        <span v-if="title || $slots.title" class="el-alert__title" :class="[ isBoldTitle ]">
          <slot name="title">{{ title }}</slot>
        </span>
        // description部分,提供默认插槽
        <p v-if="$slots.default || !!description" class="el-alert__description">
          <slot>
            {{ description }}
          </slot>
        </p>
        // 关闭按钮或文本
        <i
          v-if="closable"
          class="el-alert__closebtn"
          :class="{ 'is-customed': closeText !== '', 'el-icon-close': closeText === '' }"
          @click="close"
        >
          {{ closeText }}
        </i>
      </div>
    </div>
  </transition>
</template>

2.2 script

// 部分核心源码
setup(props, ctx) {
    // state
    const visible = ref(true)
    
    // 计算属性,控制样式
    // computed
    const typeClass = computed(() => `el-alert--${ props.type }`)
    const iconClass = computed(() => TYPE_CLASSES_MAP[props.type] || 'el-icon-info')
    const isBigIcon = computed(() => props.description || ctx.slots.default ? 'is-big' : '')
    const isBoldTitle = computed(() => props.description || ctx.slots.default ? 'is-bold' : '')

    // methods
    const close = evt => {
      visible.value = false
      ctx.emit('close', evt)
    }

    return {
      visible,
      typeClass,
      iconClass,
      isBigIcon,
      isBoldTitle,
      close,
    }
  }