Vue3组合式API实战:构建高效可复用的表格组件
一、组合式API的优势解析
Vue3的组合式API通过逻辑关注点组织代码,相比Options API具有三大优势:
- 逻辑复用:可将业务逻辑提取为独立函数
- 代码组织:相关逻辑集中维护
- 类型推导:更好的TypeScript支持
// 传统Options API vs 组合式API
export default {
data() { return { count: 0 } },
methods: { increment() { this.count++ } }
}
// 组合式API
import { ref } from 'vue'
function useCounter() {
const count = ref(0)
function increment() { count.value++ }
return { count, increment }
}
二、表格组件核心实现
1. 基础表格结构
创建可配置的表格组件模板:
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key">
{{ col.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in paginatedData" :key="index">
<td v-for="col in columns" :key="col.key">
{{ item[col.key] }}
</td>
</tr>
</tbody>
</table>
</template>
2. 组合式逻辑封装
创建useTable组合函数处理核心逻辑:
import { computed, ref } from 'vue'
export function useTable(data, options = {}) {
const { pageSize = 10 } = options
const currentPage = ref(1)
const sortKey = ref('')
const sortDirection = ref('asc')
const sortedData = computed(() => {
if (!sortKey.value) return data.value
return [...data.value].sort((a, b) => {
const modifier = sortDirection.value === 'asc' ? 1 : -1
return a[sortKey.value] > b[sortKey.value] ? modifier : -modifier
})
})
const paginatedData = computed(() => {
const start = (currentPage.value - 1) * pageSize
return sortedData.value.slice(start, start + pageSize)
})
function sortBy(key) {
if (sortKey.value === key) {
sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
} else {
sortKey.value = key
sortDirection.value = 'asc'
}
}
return { paginatedData, currentPage, sortBy, sortKey, sortDirection }
}
三、完整组件实现案例
集成所有功能的完整组件示例:
<script setup>
import { ref } from 'vue'
import { useTable } from './useTable'
const data = ref([
{ id: 1, name: '张三', age: 28 },
{ id: 2, name: '李四', age: 32 },
// ...更多数据
])
const columns = [
{ key: 'id', title: 'ID' },
{ key: 'name', title: '姓名' },
{ key: 'age', title: '年龄' }
]
const {
paginatedData,
currentPage,
sortBy,
sortKey,
sortDirection
} = useTable(data, { pageSize: 5 })
</script>
<template>
<div class="table-container">
<table>
<!-- 表头省略 -->
<!-- 表格内容省略 -->
</table>
<div class="pagination">
<button @click="currentPage--" :disabled="currentPage === 1">
上一页
</button>
<span>{{ currentPage }}</span>
<button @click="currentPage++">
下一页
</button>
</div>
</div>
</template>
四、性能优化技巧
- 使用
v-memo
优化大型表格渲染 - 虚拟滚动处理超大数据集
- 防抖处理频繁的排序操作
- 按需加载分页数据
通过组合式API的灵活组合,我们可以轻松扩展表格功能(如筛选、行选择等),同时保持代码的可维护性。