【ElementPlus】深入探索ElementPlus:前端界面的全能组件库


📚 引言

在现代 Web 开发中,创建既美观又功能强大的用户界面是一项挑战。Element Plus,作为 Vue 3 生态中的明星 UI 组件库,以其丰富的组件、优秀的性能和易用性赢得了广大开发者的青睐。

本文将全面覆盖 Element Plus 的 常用核心组件,通过 深度分析、最佳实践案例 以及 详细的代码示例,帮助你掌握如何在实际项目中高效利用 Element Plus,构建现代化、响应式的企业级应用。


🛠️ 核心组件详解与应用(含完整参数说明)

1. 🎯 el-button 按钮组件

按钮是用户界面中最基本的交互元素之一。Element Plus 的 el-button 提供了多种类型、尺寸和状态,满足各种场景需求。

✅ 参数说明(Props)

参数 类型 可选值 默认值 说明
size string large / default / small default 按钮尺寸
type string primary/ success / warning / danger / info / text 按钮类型
plain boolean false 是否为朴素按钮(背景透明,仅边框和文字)
round boolean false 是否为圆角按钮
circle boolean false 是否为圆形图标按钮
loading boolean false 是否加载中状态
disabled boolean false 是否禁用
icon string / Component 图标组件,可使用 @element-plus/icons-vue 中的图标
autofocus boolean false 是否自动聚焦
native-type string button / submit / reset button 原生 type 属性

🧩 事件(Events)

事件名 说明 回调参数
click 点击按钮时触发

💡 使用说明与示例

<template>
  <div class="button-group">
    <!-- 基础按钮 -->
    <el-button>默认按钮</el-button>
    <el-button type="primary">主要按钮</el-button>
    <el-button type="success">成功按钮</el-button>
    <el-button type="info">信息按钮</el-button>
    <el-button type="warning">警告按钮</el-button>
    <el-button type="danger">危险按钮</el-button>

    <!-- 朴素按钮 -->
    <el-button plain>朴素按钮</el-button>
    <el-button type="primary" plain>朴素主要按钮</el-button>

    <!-- 圆角按钮 -->
    <el-button round>圆角按钮</el-button>
    <el-button type="primary" round>圆角主要按钮</el-button>

    <!-- 图标按钮 -->
    <el-button type="primary" icon="Edit" circle />
    <el-button type="success" icon="Check" circle />
    <el-button type="danger" icon="Delete" circle />

    <!-- 加载状态 -->
    <el-button type="primary" :loading="true">加载中</el-button>

    <!-- 禁用状态 -->
    <el-button type="primary" disabled>禁用按钮</el-button>
  </div>
</template>

<script setup>
import { Edit, Check, Delete } from '@element-plus/icons-vue'
</script>

2. 🖼️ el-icon 图标组件

el-icon 是 Element Plus 的图标容器,用于统一管理图标样式和行为。

✅ 参数说明(Props)

参数 类型 可选值 默认值 说明
size string / number 图标大小
color string 图标颜色
class string 自定义类名

⚠️ 注意:图标本身通过默认插槽传入,如 <el-icon><Edit /></el-icon>

💡 使用说明

<template>
  <el-icon :size="20" color="#409eff">
    <Edit />
  </el-icon>
  <el-icon class="custom-icon">
    <Setting />
  </el-icon>
</template>

<script setup>
import { Edit, Setting } from '@element-plus/icons-vue'
</script>

<style>
.custom-icon {
  color: #67c23a;
  font-size: 24px;
}
</style>

3. 💬 el-message 消息提示组件

用于轻量级的全局消息提示,不打断用户操作。

✅ 方法调用(非组件 Props)

import { ElMessage } from 'element-plus'

// 基本用法
ElMessage('这是一条消息')

// 指定类型
ElMessage.success('操作成功')
ElMessage.warning('警告内容')
ElMessage.error('错误信息')
ElMessage.info('提示信息')

// 自定义配置
ElMessage({
  message: '自定义消息',
  type: 'success',
  duration: 3000, // 显示时间,毫秒
  showClose: true, // 是否显示关闭按钮
  center: true, // 文字是否居中
  offset: 60, // 距离窗口顶部的偏移量
  onClose: () => console.log('消息关闭')
})

✅ 配置项说明

参数 类型 默认值 说明
message string / VNode 消息文字
type string info 主题,可选 success / warning / error / info
icon Component 自定义图标组件
dangerouslyUseHTMLString boolean false 是否将 message 作为 HTML 片段处理
duration number 3000 显示时间,毫秒
showClose boolean false 是否显示关闭按钮
center boolean false 文字是否居中
offset number 20 距离窗口顶部的偏移量
onClose function 关闭时的回调函数

4. 🔘 el-radio 单选组件

用于在多个选项中选择一个。

el-radio Props

参数 类型 可选值 默认值 说明
model-value / v-model string / number / boolean 绑定值
label string / number / boolean Radio 的 value
disabled boolean false 是否禁用
border boolean false 是否显示边框
size string large / default / small 尺寸
name string 原生 name 属性

el-radio-group Props(用于包裹多个 radio)

参数 类型 可选值 默认值 说明
model-value / v-model string / number / boolean 绑定值
size string large / default / small 尺寸
disabled boolean false 是否禁用
text-color string #ffffff 按钮形式的 Radio 激活时的文本颜色
fill string #409eff 按钮形式的 Radio 激活时的填充色和边框色

💡 使用说明

<template>
  <!-- 基础单选 -->
  <el-radio v-model="radio" label="1">选项A</el-radio>
  <el-radio v-model="radio" label="2">选项B</el-radio>

  <!-- 带边框 -->
  <el-radio-group v-model="radio2">
    <el-radio label="1" border>选项A</el-radio>
    <el-radio label="2" border disabled>选项B</el-radio>
  </el-radio-group>

  <!-- 按钮样式 -->
  <el-radio-group v-model="radio3" size="large">
    <el-radio-button label="上海">上海</el-radio-button>
    <el-radio-button label="北京">北京</el-radio-button>
    <el-radio-button label="广州">广州</el-radio-button>
  </el-radio-group>
</template>

<script setup>
import { ref } from 'vue'
const radio = ref('1')
const radio2 = ref('1')
const radio3 = ref('上海')
</script>

5. 🔽 el-select 选择器组件

下拉选择器,支持单选、多选、搜索、远程加载等。

el-select Props

参数 类型 可选值 默认值 说明
model-value / v-model string / number / array 绑定值
multiple boolean false 是否多选
disabled boolean false 是否禁用
clearable boolean false 是否可以清空选项
filterable boolean false 是否可搜索
allow-create boolean false 是否允许用户创建新条目
loading boolean false 是否正在从远程获取数据
remote boolean false 是否为远程搜索
remote-method function 远程搜索方法
placeholder string 请选择 占位符
size string large / default / small 尺寸
collapse-tags boolean false 多选时是否将选中值按文字的形式展示
collapse-tags-tooltip boolean false 多选时折叠的标签是否显示 tooltip

el-option Props

参数 类型 可选值 默认值 说明
value string / number / boolean 选项的值
label string 选项的标签,若不设置则默认与 value 相同
disabled boolean false 是否禁用该选项

💡 使用说明

<template>
  <!-- 基础选择 -->
  <el-select v-model="value" placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>

  <!-- 多选 -->
  <el-select v-model="multipleValue" multiple placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>

  <!-- 远程搜索 -->
  <el-select
    v-model="remoteValue"
    multiple
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="remoteMethod"
    :loading="loading"
  >
    <el-option
      v-for="item in remoteOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup>
import { ref } from 'vue'

const value = ref('')
const multipleValue = ref([])
const remoteValue = ref([])
const loading = ref(false)
const remoteOptions = ref([])

const options = [
  { value: 'option1', label: '黄金糕' },
  { value: 'option2', label: '双皮奶' },
  { value: 'option3', label: '蚵仔煎' },
]

const remoteMethod = (query) => {
  if (query !== '') {
    loading.value = true
    setTimeout(() => {
      loading.value = false
      remoteOptions.value = options.filter(item => item.label.toLowerCase().includes(query.toLowerCase()))
    }, 200)
  } else {
    remoteOptions.value = []
  }
}
</script>

6. 🔀 el-switch 开关组件

用于两种状态间的切换,如开启/关闭。

✅ Props

参数 类型 可选值 默认值 说明
model-value / v-model boolean / string / number false 绑定值
disabled boolean false 是否禁用
width string / number 40 宽度
inline-prompt boolean false 是否在开关内显示文字
active-icon Component 自定义激活时的图标组件
inactive-icon Component 自定义未激活时的图标组件
active-text string 激活时的文字
inactive-text string 未激活时的文字
active-value string / number / boolean true 激活时的值
inactive-value string / number / boolean false 未激活时的值
active-color string #409eff 激活时的背景色
inactive-color string #c0ccda 未激活时的背景色
name string 原生 name 属性

💡 使用说明

<template>
  <el-switch
    v-model="value1"
    active-text="开"
    inactive-text="关"
  />

  <el-switch
    v-model="value2"
    class="ml-2"
    inline-prompt
    active-icon="Check"
    inactive-icon="Close"
  />

  <el-switch
    v-model="value3"
    class="ml-2"
    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
  />
</template>

<script setup>
import { ref } from 'vue'
import { Check, Close } from '@element-plus/icons-vue'

const value1 = ref(true)
const value2 = ref(false)
const value3 = ref(true)
</script>

7. 📝 el-form 表单组件

表单容器,用于管理表单项的布局、校验和提交。

el-form Props

参数 类型 可选值 默认值 说明
model object 表单数据对象
rules object 表单验证规则
inline boolean false 行内表单模式
label-position string top / left / right right 标签的位置
label-width string / number 标签的宽度
label-suffix string 表单域标签的后缀
hide-required-asterisk boolean false 是否隐藏必填字段的标签旁边的红色星号
require-asterisk-position string left / right left 必填字段的星号位置
show-message boolean true 是否显示校验错误信息
inline-message boolean false 是否以行内形式展示校验信息
status-icon boolean false 是否在输入框中显示校验结果图标
disabled boolean false 是否禁用该表单内的所有组件
scroll-to-error boolean false 提交表单时,如果校验失败,是否自动滚动到第一个错误表单项

el-form-item Props

参数 类型 可选值 默认值 说明
label string 标签文本
label-width string / number 标签的宽度
prop string 对应的 model 字段名,用于校验
required boolean false 是否必填
rules object / array 表单验证规则
error string 表单域的错误信息,设置后会覆盖校验规则的错误信息
show-message boolean true 是否显示校验错误信息
inline-message boolean false 是否以行内形式展示校验信息
size string large / default / small 尺寸

⚠️ 注意el-form-item 必须设置 prop 属性才能进行校验。

💡 使用说明

<template>
  <el-form
    ref="ruleFormRef"
    :model="form"
    :rules="rules"
    label-width="120px"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input-number v-model="form.age" :min="1" :max="150" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const ruleFormRef = ref()
const form = ref({
  username: '',
  email: '',
  age: 18,
})

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', message: '年龄必须为数字值', trigger: 'blur' }
  ]
})

const submitForm = async (formEl) => {
  if (!formEl) return
  try {
    await formEl.validate()
    ElMessage.success('提交成功!')
  } catch (error) {
    console.log('校验失败', error)
  }
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

8. 📊 el-table 表格组件

用于展示大量结构化数据。

el-table Props

参数 类型 可选值 默认值 说明
data array 显示的数据
height string / number 表格高度
max-height string / number 表格最大高度
stripe boolean false 是否为斑马纹 table
border boolean false 是否带有纵向边框
fit boolean true 列的宽度是否自撑开
show-header boolean true 是否显示表头
highlight-current-row boolean false 是否要高亮当前行
current-row-key string / number 当前行的 key,只写属性
row-class-name string / function 行的 className 的回调方法
row-style object / function 行的 style 的回调方法
cell-class-name string / function 单元格的 className 的回调方法
cell-style object / function 单元格的 style 的回调方法
header-row-class-name string / function 表头行的 className 的回调方法
header-row-style object / function 表头行的 style 的回调方法
header-cell-class-name string / function 表头单元格的 className 的回调方法
header-cell-style object / function 表头单元格的 style 的回调方法
row-key string / function 行数据的 Key,用来优化渲染
empty-text string 暂无数据 空数据时显示的文本内容
default-expand-all boolean false 是否默认展开所有行
expand-row-keys array 可以通过该属性设置展开的行,需要设置 row-key
default-sort object 默认的排序列的 prop 和顺序
tooltip-effect string dark / light dark tooltip 的 effect 属性
show-summary boolean false 是否在表尾显示合计行
sum-text string 合计 合计行第一列的文本
summary-method function 自定义的合计计算方法
span-method function 合并行或列的计算方法
select-on-indeterminate boolean true 在多选表格中,当仅有部分行被选中时,点击表头的多选框是否选择所有项
indent number 16 展示树形数据时,树节点的缩进
lazy boolean false 是否懒加载子节点数据
load function 加载子节点数据的函数
tree-props object { hasChildren: 'hasChildren', children: 'children' } 渲染嵌套数据的配置选项

el-table-column Props

参数 类型 可选值 默认值 说明
type string selection / index / expand 列类型
index number / function 如果 typeindex,可以通过 index 属性设置行索引
column-key string column 的 key,如果需要使用 filter-change 事件,则需此属性
label string 显示的标题
prop string 对应列内容的字段名
width string / number 对应列的宽度
min-width string / number 对应列的最小宽度
fixed string / boolean true / left / right 列是否固定
render-header function 列标题 Label 区域渲染使用的 Function
sortable boolean / string true / false / custom false 对应列是否可以排序
sort-method function 对数据进行排序的时候使用的方法
resizable boolean true 对应列是否可以通过拖动改变宽度
formatter function 用来格式化内容
show-overflow-tooltip boolean false 当内容过长被隐藏时是否显示 tooltip
align string left / center / right left 对齐方式
header-align string left / center / right 表头对齐方式,若不设置,则继承 align 的值
class-name string 列的 className
label-class-name string 当前列标题的自定义类名
selectable function 仅对 type="selection" 的列有效,类型为 Function,Function 的返回值用来决定这一行的 checkbox 是否可以勾选
reserve-selection boolean false 仅对 type="selection" 的列有效,类型为 Boolean,为 true 则会在数据更新之后保留之前选中的选项
filters array 数据筛选的选项,数组格式,数组中的元素需要有 text 和 value 属性
filter-placement string top / top-start / top-end / bottom / bottom-start / bottom-end / left / left-start / left-end / right / right-start / right-end 过滤弹出框的定位
filter-multiple boolean true 数据筛选的选项是否多选
filter-method function 数据筛选使用的方法,如果是多选的筛选项,对每一条数据会执行多次,任意一次返回 true 就会显示
filtered-value array 选中的数据筛选项,如果设置了这个值,列的筛选状态会受控于外部

⚠️ 注意:由于篇幅限制,el-table 的事件、方法和插槽未在此详述,但它们同样重要,如 @selection-change@sort-change@filter-change 等。

💡 使用说明

<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    height="400"
    border
    stripe
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" width="60" />
    <el-table-column prop="name" label="姓名" width="120" />
    <el-table-column prop="age" label="年龄" width="100" sortable />
    <el-table-column prop="address" label="地址" show-overflow-tooltip />
    <el-table-column label="操作" width="180">
      <template #default="{ row }">
        <el-button size="small" @click="handleEdit(row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { ref } from 'vue'

const tableData = ref([
  { name: '张三', age: 25, address: '上海市普陀区金沙江路 1518 弄' },
  { name: '李四', age: 30, address: '上海市普陀区金沙江路 1517 弄' },
  { name: '王五', age: 28, address: '上海市普陀区金沙江路 1519 弄' }
])

const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleEdit = (row) => {
  console.log('编辑', row)
}

const handleDelete = (row) => {
  console.log('删除', row)
}
</script>

9. 🍽️ el-menu 菜单组件

用于构建导航菜单。

el-menu Props

参数 类型 可选值 默认值 说明
mode string horizontal / vertical vertical 菜单模式
collapse boolean false 是否水平折叠收起菜单
background-color string #ffffff 菜单的背景色
text-color string #303133 菜单的文字颜色
active-text-color string #409eff 菜单激活时的文字颜色
default-active string 当前激活菜单的 index
default-openeds array 当前打开的 sub-menu 的 index 的数组
unique-opened boolean false 是否只保持一个子菜单的展开
menu-trigger string hover / click hover 子菜单打开的触发方式
router boolean false 是否使用 vue-router 的模式,启用该模式会在激活导航时以 index 作为 path 进行路由跳转
collapse-transition boolean true 是否开启折叠动画

el-menu-item Props

参数 类型 可选值 默认值 说明
index string 唯一标志
route object / string Vue Router 路径对象或字符串
disabled boolean false 是否禁用

el-sub-menu Props

参数 类型 可选值 默认值 说明
index string 唯一标志
popper-class string 弹出菜单的自定义类名
popper-offset number 6 弹出菜单和父菜单的距离
teleported boolean true 是否将弹出菜单放置于 body 内

💡 使用说明

<template>
  <el-menu
    :default-active="activeIndex"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"
  >
    <el-menu-item index="1">处理中心</el-menu-item>
    <el-sub-menu index="2">
      <template #title>我的工作台</template>
      <el-menu-item index="2-1">选项1</el-menu-item>
      <el-menu-item index="2-2">选项2</el-menu-item>
      <el-menu-item index="2-3">选项3</el-menu-item>
    </el-sub-menu>
    <el-menu-item index="3" disabled>消息中心</el-menu-item>
    <el-menu-item index="4">订单管理</el-menu-item>
  </el-menu>
</template>

<script setup>
import { ref } from 'vue'

const activeIndex = ref('1')

const handleSelect = (key, keyPath) => {
  console.log(key, keyPath)
}
</script>

10. 🧱 el-layout 布局组件

用于构建页面整体布局。

el-container Props

参数 类型 可选值 默认值 说明
direction string horizontal / vertical 子元素的排列方向

el-header Props

参数 类型 可选值 默认值 说明
height string 60px 顶栏高度

el-aside Props

参数 类型 可选值 默认值 说明
width string 300px 侧边栏宽度

el-main Props

参数 类型 可选值 默认值 说明
无特殊参数

el-footer Props

参数 类型 可选值 默认值 说明
height string 60px 底栏高度

💡 使用说明

<template>
  <el-container style="height: 100vh;">
    <el-aside width="200px">
      <el-menu
        default-active="1"
        class="el-menu-vertical-demo"
        @open="handleOpen"
        @close="handleClose"
      >
        <el-menu-item index="1">
          <el-icon><Location /></el-icon>
          <span>导航一</span>
        </el-menu-item>
        <el-menu-item index="2">
          <el-icon><Menu /></el-icon>
          <span>导航二</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header>Header</el-header>
      <el-main>Main Content</el-main>
      <el-footer>Footer</el-footer>
    </el-container>
  </el-container>
</template>

<script setup>
import { Location, Menu } from '@element-plus/icons-vue'
const handleOpen = (key, keyPath) => {
  console.log(key, keyPath)
}
const handleClose = (key, keyPath) => {
  console.log(key, keyPath)
}
</script>

11. 📦 el-container 组件

已在 el-layout 部分介绍。


用于实现图片或内容的轮播展示。

el-carousel Props

参数 类型 可选值 默认值 说明
height string 轮播图的高度
initial-index number 0 初始显示的索引
trigger string hover / click hover 指示器的触发方式
autoplay boolean true 是否自动切换
interval number 3000 自动切换的时间间隔,单位为毫秒
indicator-position string none / outside / inside 指示器的位置
arrow string always / hover / never hover 切换箭头的显示时机
type string card / — 走马灯的类型
loop boolean true 是否循环显示
direction string horizontal / vertical horizontal 滚动方向

el-carousel-item Props

参数 类型 可选值 默认值 说明
无特殊参数

💡 使用说明

<template>
  <el-carousel height="200px">
    <el-carousel-item v-for="item in 4" :key="item">
      <h3 class="small justify-center">{{ item }}</h3>
    </el-carousel-item>
  </el-carousel>
</template>

<style>
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>

13. 📜 el-scrollbar 滚动条组件

el-scrollbar 是一个自定义滚动条组件,用于替代浏览器原生的滚动条,提供更美观、更可控的滚动体验。它特别适用于需要在固定高度或宽度的容器内展示大量内容的场景。

✅ Props

参数 类型 可选值 默认值 说明
height string / number 设置滚动条容器的高度
max-height string / number 设置滚动条容器的最大高度
native boolean false 是否使用原生滚动条,如果为 true,则不会自定义滚动条样式,而是使用浏览器原生滚动条
wrap-style object / string 外层容器 wrap的自定义样式
wrap-class string / object / array 外层容器 wrap的自定义类名
view-class string / object / array 内容视图 view的自定义类名
view-style object / string 内容视图 view的自定义样式
noresize boolean false 防止 resize事件触发重新计算
tag string div 视图的元素标签名
always boolean false 是否总是显示滚动条

✅ 事件 (Events)

事件名 说明 回调参数
scroll 滚动时触发 scroll:

✅ 方法 (Methods)

方法名 说明 参数
handleScroll 手动触发滚动事件
scrollTo 将内容滚动到指定的位置 options: 可以是数字(表示 scrollTop)或包含 topleft 的对象
getScrollTop 获取当前滚动的垂直位置
setScrollTop 设置垂直滚动位置 scrollTop: 滚动位置
getScrollLeft 获取当前滚动的水平位置
setScrollLeft 设置水平滚动位置 scrollLeft: 滚动位置

💡 使用说明与示例

el-scrollbar 组件非常适合用于创建自定义的滚动区域,比如侧边栏菜单、对话框内容区、代码预览窗格等。

<template>
  <div class="scrollbar-container">
    <!-- 基础垂直滚动条 -->
    <el-scrollbar height="200px">
      <p v-for="item in 20" :key="item" class="scrollbar-demo-item">{{ item }}</p>
    </el-scrollbar>

    <!-- 带有自定义样式的滚动条 -->
    <el-scrollbar 
      height="200px" 
      :wrap-style="{ 'background': 'rgb(235, 235, 235)' }"
      :always="true"
    >
      <p v-for="item in 20" :key="item" class="scrollbar-demo-item">{{ item }}</p>
    </el-scrollbar>

    <!-- 水平和垂直滚动条 -->
    <el-scrollbar height="200px" style="width: 300px;">
      <div style="width: 800px; white-space: nowrap;">
        <span v-for="item in 50" :key="item" class="scrollbar-demo-item" style="display: inline-block;">
          {{ item }}
        </span>
      </div>
    </el-scrollbar>

    <!-- 监听滚动事件 -->
    <el-scrollbar height="200px" @scroll="onScroll">
      <p v-for="item in 30" :key="item" class="scrollbar-demo-item">监听滚动 - {{ item }}</p>
    </el-scrollbar>
    <p>滚动位置: {{ scrollPosition }}</p>

    <!-- 使用方法控制滚动 -->
    <el-scrollbar ref="scrollbarRef" height="200px">
      <p v-for="item in 50" :key="item" class="scrollbar-demo-item">可编程控制 - {{ item }}</p>
    </el-scrollbar>
    <div class="control-buttons">
      <el-button @click="scrollToTop">滚动到顶部</el-button>
      <el-button @click="scrollToBottom">滚动到底部</el-button>
      <el-button @click="scrollToPosition">滚动到位置 1000</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElScrollbar, ElButton } from 'element-plus'

const scrollPosition = ref({ scrollLeft: 0, scrollTop: 0 })
const scrollbarRef = ref()

const onScroll = (scroll) => {
  scrollPosition.value = scroll
}

const scrollToTop = () => {
  scrollbarRef.value?.setScrollTop(0)
}

const scrollToBottom = () => {
  // 获取内容总高度并滚动到底部
  const wrapElement = scrollbarRef.value?.wrap$ 
  if (wrapElement) {
    scrollbarRef.value?.setScrollTop(wrapElement.scrollHeight - wrapElement.clientHeight)
  }
}

const scrollToPosition = () => {
  scrollbarRef.value?.setScrollTop(1000)
}
</script>

<style scoped>
.scrollbar-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.control-buttons {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
</style>

🎯 应用场景

  1. 固定高度内容区域:当需要在一个固定大小的容器内展示可能超出其范围的内容时,如侧边栏、弹窗内容、列表预览等。
  2. 美化滚动体验:原生滚动条在不同操作系统上样式不一,且可能占用过多空间。el-scrollbar 提供了更精致、更一致的视觉效果。
  3. 精确控制滚动:通过其提供的方法,可以精确控制滚动位置,实现平滑滚动、锚点跳转等高级功能。
  4. 性能优化:在某些情况下,使用虚拟滚动结合 el-scrollbar 可以优化大量数据的渲染性能。

⚠️ 注意事项

  • 性能:虽然 el-scrollbar 提供了更好的视觉体验,但它是一个 JavaScript 实现的组件,对于非常长的列表,可能会比原生滚动条消耗更多性能。在极端情况下,考虑使用 native="true" 或虚拟滚动技术。
  • 触摸设备:确保在移动设备上的触摸滚动体验是流畅的。
  • 样式覆盖:可以通过 wrap-classview-class 等属性或深度选择器来自定义滚动条的外观。

14. 💬 el-tooltip 文字提示组件

el-tooltip 组件用于当目标元素的文本内容过长被省略时,鼠标悬停时显示完整内容,或者用于对某个元素进行简短说明。

✅ Props

参数 类型 可选值 默认值 说明
model-value / v-model boolean 状态是否可见
content string 显示的内容,也可以通过 slot#content 传入 DOM
placement string top / top-start / top-end / bottom / bottom-start / bottom-end / left / left-start / left-end / right / right-start / right-end bottom 出现位置
value-on-clear boolean 清除时的值
disabled boolean false 是否禁用
offset number 0 出现位置的偏移量
transition string el-fade-in-linear 定义渐变动画
visible-arrow boolean true 是否显示箭头
popper-options object { boundariesElement: 'body', gpuAcceleration: false } popper.js 参数
open-delay number 0 出现之前的延迟(毫秒),仅在 triggerhover 时有效
close-delay number 200 消失之前的延迟(毫秒),仅在 triggerhover 时有效
tabindex number / string 0 tooltip 的 tabindex
show-after number 0 显示延迟,单位毫秒
hide-after number 0 关闭延迟,单位毫秒
auto-close number 0 点击后自动关闭延时,单位毫秒
manual boolean false 是否手动控制状态,true 则不会自动显示隐藏
effect string dark / light dark 默认提供的主题
enterable boolean true 鼠标是否可以进入 tooltip
hide-on-click boolean false 是否在点击后隐藏
popper-class string 为 popper 添加类名,可用于自定义样式
popper-style object 为 popper 添加内联样式
trigger string hover / focus / click / manual hover 触发方式
virtual-ref object 虚拟元素的 ref,用于与其引用的元素进行交互
virtual-triggering boolean true 是否触发虚拟元素事件
teleported boolean true tooltip 是否会被插入到 body 元素上
persistent boolean false tooltip 是否会对 v-model 进行响应

✅ 事件 (Events)

事件名 说明 回调参数
show tooltip 显示时触发
hide tooltip 隐藏时触发

✅ Slots

插槽名 说明
内容,也可以使用 content 属性
content 内容,当需要传入 DOM 时使用

💡 使用说明与示例

el-tooltip 是提升用户体验的重要组件,常用于按钮、表格单元格、标签等元素的说明。

<template>
  <div class="tooltip-container">
    <!-- 基础用法 -->
    <el-tooltip content="这是一段提示文字" placement="top">
      <el-button>顶部显示</el-button>
    </el-tooltip>

    <el-tooltip content="这是一段提示文字" placement="bottom">
      <el-button>底部显示</el-button>
    </el-tooltip>

    <el-tooltip content="这是一段提示文字" placement="left">
      <el-button>左侧显示</el-button>
    </el-tooltip>

    <el-tooltip content="这是一段提示文字" placement="right">
      <el-button>右侧显示</el-button>
    </el-tooltip>

    <!-- 主题与效果 -->
    <el-tooltip content="深色主题" effect="dark">
      <el-button>深色</el-button>
    </el-tooltip>

    <el-tooltip content="浅色主题" effect="light">
      <el-button>浅色</el-button>
    </el-tooltip>

    <!-- 延迟显示与关闭 -->
    <el-tooltip content="延迟显示" :open-delay="500" :close-delay="300">
      <el-button>延迟显示</el-button>
    </el-tooltip>

    <!-- 点击触发 -->
    <el-tooltip content="点击显示提示" trigger="click">
      <el-button>点击触发</el-button>
    </el-tooltip>

    <!-- 手动控制 -->
    <el-tooltip v-model="visible" content="手动控制的提示" :manual="true" placement="top">
      <template #content>
        <span>这是 <b>加粗</b> 的提示内容</span>
      </template>
      <el-button @click="visible = !visible">手动控制</el-button>
    </el-tooltip>

    <!-- 复杂内容 -->
    <el-tooltip placement="top">
      <template #content>
        <div>多行内容</div>
        <div><el-tag size="small">标签</el-tag></div>
      </template>
      <el-button>复杂内容</el-button>
    </el-tooltip>

    <!-- 禁用状态 -->
    <el-tooltip content="禁用的提示" disabled>
      <el-button disabled>禁用按钮</el-button>
    </el-tooltip>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElTooltip, ElButton, ElTag } from 'element-plus'

const visible = ref(false)
</script>

<style scoped>
.tooltip-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 20px;
}
</style>

🎯 应用场景

  1. 按钮说明:为功能图标或简短按钮文字提供详细说明。
  2. 表格内容溢出:当表格单元格内容过长被截断时,鼠标悬停显示完整内容。
  3. 表单验证提示:在输入框旁边提供格式或要求的提示。
  4. 导航菜单:在侧边栏图标菜单中,鼠标悬停显示菜单名称。
  5. 状态说明:对某些状态标签或徽章提供更详细的解释。

⚠️ 注意事项

  • 内容长度:避免在 tooltip 中放置过多内容,通常应保持简短。
  • 可访问性:确保 tooltip 内容对屏幕阅读器等辅助技术是可访问的。
  • 触发方式:根据使用场景选择合适的触发方式(hover, click, focus)。
  • 移动端:在触摸设备上,hover 触发可能不理想,考虑使用 click 触发。

15. 🔽 el-collapse 折叠面板组件

el-collapse 组件用于实现内容的折叠与展开,可以有效节省页面空间,让用户按需查看信息。

✅ Props

参数 类型 可选值 默认值 说明
model-value / v-model array / string 当前激活的面板的 name,如果是手风琴模式,则为字符串
accordion boolean false 是否启用手风琴模式,即每次只允许展开一个面板

✅ 事件 (Events)

事件名 说明 回调参数
update:model-value 激活面板时触发 (activeNames: array / string)
change 激活面板时触发(与 update:model-value 类似) (activeNames: array / string)

✅ 插槽 (Slots)

插槽名 说明 子组件
默认插槽,用于放置 el-collapse-item 组件 el-collapse-item

el-collapse-item Props

参数 类型 可选值 默认值 说明
name string / number 唯一标志符,v-model 的值
title string 面板标题
disabled boolean false 是否禁用

💡 使用说明与示例

el-collapse 是组织分组信息的理想选择,常用于 FAQ、配置面板、详情页等。

<template>
  <div class="collapse-container">
    <!-- 基础折叠面板 -->
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item name="1">
        <template #title>
          一致性 Consistency<i class="header-icon el-icon-info"></i>
        </template>
        <div>与现实生活一致:与现实生活的流程、逻辑保持一致,遵循用户习惯的语言和概念;</div>
        <div>在界面中一致:所有的元素和结构需保持一致,比如:设计样式、图标和文本、元素的位置等。</div>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template #title>
          反馈 Feedback
        </template>
        <div>控制反馈:通过界面样式和交互动效让用户可以清晰的感知自己的操作;</div>
        <div>页面反馈:页面操作后,告知用户操作成功。</div>
      </el-collapse-item>
      <el-collapse-item name="3" disabled>
        <template #title>
          效率 Efficiency
        </template>
        <div>简化流程:设计简洁直观的操作流程;</div>
        <div>清晰明确:语言表达清晰且表意明确,让用户快速理解进而作出决策;</div>
        <div>帮助用户识别:界面简单直白,让用户快速识别而非回忆,减少用户记忆负担。</div>
      </el-collapse-item>
      <el-collapse-item name="4">
        <template #title>
          可控 Controllability
        </template>
        <div>用户决策:根据场景可给予用户操作建议或安全提示,但不能代替用户进行决策;</div>
        <div>权限:尊重用户的选择,包括取消操作的权利。</div>
      </el-collapse-item>
    </el-collapse>

    <!-- 手风琴模式 -->
    <h3>手风琴模式</h3>
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item name="1">
        <template #title>
          一致性 Consistency<i class="header-icon el-icon-info"></i>
        </template>
        <div>与现实生活一致:与现实生活的流程、逻辑保持一致,遵循用户习惯的语言和概念;</div>
        <div>在界面中一致:所有的元素和结构需保持一致,比如:设计样式、图标和文本、元素的位置等。</div>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template #title>
          反馈 Feedback
        </template>
        <div>控制反馈:通过界面样式和交互动效让用户可以清晰的感知自己的操作;</div>
        <div>页面反馈:页面操作后,告知用户操作成功。</div>
      </el-collapse-item>
      <el-collapse-item name="3">
        <template #title>
          效率 Efficiency
        </template>
        <div>简化流程:设计简洁直观的操作流程;</div>
        <div>清晰明确:语言表达清晰且表意明确,让用户快速理解进而作出决策;</div>
        <div>帮助用户识别:界面简单直白,让用户快速识别而非回忆,减少用户记忆负担。</div>
      </el-collapse-item>
      <el-collapse-item name="4">
        <template #title>
          可控 Controllability
        </template>
        <div>用户决策:根据场景可给予用户操作建议或安全提示,但不能代替用户进行决策;</div>
        <div>权限:尊重用户的选择,包括取消操作的权利。</div>
      </el-collapse-item>
    </el-collapse>

    <!-- 动态控制 -->
    <div class="control-section">
      <el-button @click="toggleAll">切换所有面板</el-button>
      <el-button @click="expandFirst">展开第一个</el-button>
      <el-button @click="collapseAll">收起所有</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElCollapse, ElCollapseItem, ElButton } from 'element-plus'

const activeNames = ref(['1'])
const activeName = ref('1')

const handleChange = (val) => {
  console.log('Collapse changed:', val)
}

const toggleAll = () => {
  if (activeNames.value.length === 0) {
    activeNames.value = ['1', '2', '4'] // 排除禁用的项
  } else {
    activeNames.value = []
  }
}

const expandFirst = () => {
  activeNames.value = ['1']
}

const collapseAll = () => {
  activeNames.value = []
}
</script>

<style scoped>
.collapse-container {
  padding: 20px;
}

.collapse-container h3 {
  margin: 20px 0 10px 0;
  font-weight: normal;
  color: #666;
}

.header-icon {
  margin-left: 5px;
  color: #999;
}

.control-section {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}
</style>

🎯 应用场景

  1. FAQ 页面:常见问题解答,用户点击问题展开查看答案。
  2. 配置面板:将复杂的配置项分组折叠,用户按需展开设置。
  3. 详情页:在商品详情、用户详情等页面中,将次要信息折叠。
  4. 表单分组:在长表单中,将相关字段分组并可折叠。
  5. 文档/帮助中心:组织层级化的帮助文档。

⚠️ 注意事项

  • 内容组织:合理划分折叠项,确保每个面板内的内容主题明确。
  • 默认展开:根据用户最可能查看的内容,合理设置默认展开的面板。
  • 手风琴模式:当信息具有互斥性或需要用户逐项查看时,使用手风琴模式。
  • 性能:对于包含大量动态内容的折叠面板,考虑懒加载或条件渲染以优化性能。

posted @ 2025-08-16 16:46  青昔&  阅读(605)  评论(0)    收藏  举报