写vue可排序表格组件结合html的代码
时间: 2023-12-29 12:03:34 浏览: 47
vue数组对象排序的实现代码
下面是一个简单的可排序表格组件的Vue代码:
```html
<template>
<div>
<table>
<thead>
<tr>
<th v-for="(column, index) in columns" :key="index" @click="sortBy(column)">
{{ column }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in sortedData" :key="index">
<td v-for="(column, index) in columns" :key="index">{{ item[column] }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: {
data: {
type: Array,
required: true,
},
columns: {
type: Array,
required: true,
},
},
data() {
return {
sortDirection: '',
sortedColumn: '',
};
},
computed: {
sortedData() {
const data = [...this.data];
if (this.sortedColumn !== '') {
data.sort((a, b) => {
const A = a[this.sortedColumn];
const B = b[this.sortedColumn];
if (A < B) {
return this.sortDirection === 'asc' ? -1 : 1;
}
if (A > B) {
return this.sortDirection === 'asc' ? 1 : -1;
}
return 0;
});
}
return data;
},
},
methods: {
sortBy(column) {
if (this.sortedColumn === column) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortedColumn = column;
this.sortDirection = 'asc';
}
},
},
};
</script>
```
使用时,可以在父组件中传入数据和列名,如下所示:
```html
<template>
<div>
<sortable-table :data="tableData" :columns="tableColumns"></sortable-table>
</div>
</template>
<script>
import SortableTable from './SortableTable.vue';
export default {
components: {
SortableTable,
},
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 20 },
],
tableColumns: ['id', 'name', 'age'],
};
},
};
</script>
```
阅读全文