在Vue.js中,使用表格来展示数据是一项常见的任务。本文将为大家解析和注释一个Vue.js可滚动表格组件的代码,帮助读者更好地理解和使用该组件
html
<template>
<!-- 表格外层容器 -->
<view class="scroll-table-wrapper">
<view class="scroll-table-container">
<!-- 表格 -->
<table class="scroll-table">
<!-- 表头 -->
<thead>
<tr>
<!-- 根据列配置循环生成表头 -->
<th v-for="(item, index) in columns" :key="index">
{{ item.title }}
</th>
</tr>
</thead>
<!-- 表格内容 -->
<tbody v-if="dataSource.length > 0">
<!-- 根据数据源循环生成表格行 -->
<tr v-for="(row, rowIndex) in dataSource" :key="rowIndex">
<!-- 根据列配置循环生成单元格 -->
<td v-for="(cell, cellIndex) in columns" :key="cellIndex">
<!-- 单元格内容 -->
<view
:style="{'width': cell.width, 'white-space': cell.width ? 'normal' : 'nowrap', 'text-align': 'center'}">
{{ row[cell.dataIndex] || '' }}
<!-- 显示箭头并绑定点击事件 -->
<span v-if="arrows && cellIndex === columns.length - 1" class="arrow-icon"
@click="handleArrowClick(row, cell, type)">
<u-icon class="border-item" style="margin-left: 20rpx; display: inline-block;" name="arrow-right"
color="#000" size="12"></u-icon>
</span>
</view>
</td>
</tr>
</tbody>
<!-- 若数据源为空 -->
<tbody v-else>
<tr style="text-align: center;">
<td :colspan="columns.length">暂无数据</td>
</tr>
</tbody>
</table>
</view>
</view>
</template>
js
<script>
export default {
props: {
columns: {
type: Array,
required: true
},
dataSource: {
type: Array,
required: true
},
// 状态
type: {
type: String,
default: ''
},
// 箭头点击是否显示
arrows: {
type: Boolean,
default: false
},
},
methods: {
// 箭头点击事件
handleArrowClick(item, type) {
// 触发父组件的 show 事件,并传递相关参数
this.$emit('update:show', {
item,
type: this.type
})
}
}
}
</script>
css
<style scoped>
.scroll-table-wrapper {
min-width: 100%;
overflow-x: auto;
}
.scroll-table-container {
min-width: 100%;
display: inline-block;
white-space: nowrap;
}
.scroll-table {
border-collapse: collapse;
min-width: 100%;
table-layout: fixed;
}
th,
td {
padding: 10px;
border: 1px solid #eaeaea;
}
th {
background-color: #e0ffe7;
font-weight: bold;
}
.cell-width {
width: 100px;
}
</style>
父组件使用
<template>
<div>
<!-- 在父组件中使用可滚动表格组件 -->
<ScrollTable :columns="tableColumns" :dataSource="tableData" :arrows="true" @update:show="handleShow"></ScrollTable>
</div>
</template>
<script>
import ScrollTable from '@/components/ScrollTable.vue'; // 导入可滚动表格组件
export default {
components: {
ScrollTable, // 注册可滚动表格组件
},
data() {
return {
tableColumns: [ // 表格列配置
{ title: '姓名', dataIndex: 'name', width: '100px' },
{ title: '年龄', dataIndex: 'age', width: '80px' },
{ title: '性别', dataIndex: 'gender', width: '80px' },
],
tableData: [ // 表格数据源
{ name: '张三', age: 25, gender: '男' },
{ name: '李四', age: 30, gender: '女' },
{ name: '王五', age: 28, gender: '男' },
],
};
},
methods: {
handleShow(item, type) {
// 处理点击事件的逻辑
console.log('显示详细信息', item, type);
},
},
};
</script>