[Element Plus 源码解析] Badge 标记

1,177 阅读1分钟

一、组件介绍

官网链接:Badge 组件 | Element (gitee.io)

Badge组件常用于信息提示,如显示有xx条的通知/待办。

1.1 属性

  • value: number|string类型;标记中显示的值;
  • max: number类型,表示标记的最大值,超过最大值会显示 '{max}+',当value是number类型时生效;
  • type: string类型,表示标记的类型,有五种类型可选primary / success / warning / danger / info,默认是primary类型;
  • hidden: boolean类型,是否隐藏标记,默认值false;
  • is-dot: boolean类型,标记是否显示为圆点,默认值是false;

二、源码分析

2.1 template

<template>
  <div class="el-badge">
    // 默认插槽
    <slot></slot>
    // 过渡效果
    <transition name="el-zoom-in-center">
      // 原生sup标签
      <sup
        v-show="!hidden && (content || content === 0 || isDot)"
        class="el-badge__content"
        :class="[
          'el-badge__content--' + type,
          {
            'is-fixed': $slots.default,
            'is-dot': isDot
          }
        ]"
        v-text="content"
      >
      </sup>
    </transition>
  </div>
</template>

2.2 script

setup(props) {
    // 计算属性,动态生成content
    const content = computed(() => {
      if (props.isDot) {
        return
      }
      // max属性在value是number类型时生效
      if (typeof props.value === 'number' && typeof props.max === 'number') {
        // 超过max时,显示成max+
        return props.max < props.value ? `${props.max}+` : props.value
      }
      return props.value
    })
    return {
      content,
    }
  }