Vue3 + Typescript 实现灵活丰富的表格组件
一、引言
在前端开发中,表格组件是非常常见且功能需求较为复杂的一种组件。Vue3的发布为我们带来了更加灵活和强大的组件开发能力,结合Typescript的类型安全,我们可以创建出既健壮又易扩展的表格组件。本文将详细讲解如何使用Vue3和Typescript来实现一个包含表格编辑和拖拽功能的表格组件。
二、环境准备
在开始之前,请确保你已经安装了Node.js和Vue CLI,并且已经创建了一个Vue3 + Typescript的项目。
三、创建表格组件
-
在
src/components
目录下创建一个新文件Table.vue
。 -
在
Table.vue
中编写模板、脚本和样式。
<template>
<div>
<table>
<thead>
<tr>
<th v-for="(column, index) in columns" :key="index">
{
{ column.label }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in data" :key="rowIndex">
<td v-for="(column, columnIndex) in columns" :key="columnIndex">
<input
v-if="column.editable"
type="text"
v-model="row[column.prop]"
/>
<span v-else>{
{ row[column.prop] }}</span>
</td>
</tr>
</tbody>
</table>
</div>
</template>
脚本部分 (<script lang="ts">
):
<script lang="ts">
import {
defineComponent, PropType } from 'vue';
interface Column {
label: string;
prop: string;
editable?: boolean;
}
interface TableRow {
[key: string]: any;
}
export default defineComponent({
name: