为了实现对表格的排序和过滤功能,我们需要在 Vue 组件中添加相应的逻辑来处理这些功能。以下是一个简单的示例来指导你如何实现:
首先,我们将在数据对象中添加两个新属性来存储排序和过滤的选项:
javascript
data() {
return {
tableList: [], // 你的表格数据
// ...
sortOptions: {
lastLoginTime: null, // null: default, 'asc': ascending, 'desc': descending
userFlowSum: null, // null: default, 'asc': ascending, 'desc': descending
},
filterOptions: {
userRole: '' // 空字符串表示没有过滤
},
// ...
};
},
为了实现排序和过滤,我们将使用计算属性来处理排序和过滤逻辑:
javascript
computed: {
filteredAndSortedTableList() {
let list = this.tableList;
// 过滤逻辑
if (this.filterOptions.userRole) {
list = list.filter(row => row.userRole === this.filterOptions.userRole);
}
// 排序逻辑
if (this.sortOptions.lastLoginTime) {
list = list.sort((a, b) => {
if (this.sortOptions.lastLoginTime === 'asc') {
return new Date(a.lastLoginTime) - new Date(b.lastLoginTime);
} else if (this.sortOptions.lastLoginTime === 'desc') {
return new Date(b.lastLoginTime) - new Date(a.lastLoginTime);
}
});
}
if (this.sortOptions.userFlowSum) {
list = list.sort((a, b) => {
if (this.sortOptions.userFlowSum === 'asc') {
return a.userFlowSum - b.userFlowSum;
} else if (this.sortOptions.userFlowSum === 'desc') {
return b.userFlowSum - a.userFlowSum;
}
});
}
return list;
}
},
接下来,在模板中绑定排序和过滤:
html
<tr>
<th>选择<el-checkbox v-model="checked" /></th>
<th>登录账户</th>
<th>用户名称</th>
<th @click="toggleSort('userFlowSum')">流量使用</th>
<th>权限
<el-select v-model="filterOptions.userRole" placeholder="请选择">
<!-- 假设 'rolesList' 包含所有可能的权限角色 -->
<el-option v-for="role in rolesList" :key="role" :label="role" :value="role" />
</el-select>
</th>
<th @click="toggleSort('lastLoginTime')">最近登录时间</th>
<th>操作</th>
</tr>
然后,添加排序切换实现函数 toggleSort:
javascript
methods: {
toggleSort(key) {
// 切换排序状态
if (this.sortOptions[key] === 'asc') {
this.sortOptions[key] = 'desc';
} else {
this.sortOptions[key] = 'asc';
}
// 重置其他排序条件,以便每次只按一个条件排序
for (let otherKey in this.sortOptions) {
if (otherKey !== key) {
this.sortOptions[otherKey] = null;
}
}
},
// ...
}
最后,在模板的 <tbody> 中,替换 tableList 为计算属性 filteredAndSortedTableList:
html
<tbody>
<tr v-for="row in filteredAndSortedTableList" :key="row.userId">
<!-- ... -->
</tr>
</tbody>
以上示例将添加简单的点击标题排序和选择过滤器以过滤特定数据的表格功能。请记得在你的实际应用程序中根据实际需求进行相应的调整。