javascript - Vue.js 表格排序 (HTML & Buefy)
问题描述
我在当前项目中使用 Vue.js。情况是这样的:几乎所有的表都使用 Buefy's 并且有它的内置排序(下面的例子)。我认为这是最简单的方法。此处的文档:https ://buefy.github.io/documentation/table
<template>
<section>
<b-table default-sort="user.first_name">
<template slot-scope="props">
<b-table-column field="id" label="ID" sortable>
</b-table-column>
<b-table-column field="user.first_name" label="First Name"> </b-table-column>
<b-table-column field="user.last_name" label="Last Name">
</b-table-column>
<b-table-column field="date" label="Date">
</b-table-column>
</template>
</b-table>
</section>
</template>
然后在项目中有一个组件,它被制作成一个普通的 HTML 表格(下面的例子)。表格数据行出现在此 Slot 组件内。
<template>
<table class="classname">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<slot></slot>
</tbody>
</table>
</template>
上例的父组件是这样的(examplecomponent 是 HTML 表格生成的组件的名称):
<div class="grid">
<examplecomponent :class="exampleclass">
<template v-for="(row, index) in filteredList">
<othercomponent></othercomponent>
<othercomponenttwo></othercomponenttwo>
</template>
</examplecomponent>
</div>
所以,问题是..在这种情况下对数据进行排序的最简单/最好的方法是什么?我尝试将 HTML 表更改为使用 Buefy 的 b 表,但效果不佳。我的猜测是父组件的元素也必须更改。在 HTML 表所在的 .vue 中没有任何导入,但父级可以访问所有必要的信息。
作为一名程序员,我有点困惑而且还很陌生,所以如果有人可以帮助我并像你告诉一个 5 岁的孩子一样详细地解释一切,我会很高兴。
解决方案
我实际上自己解决了自己的问题,但花了一些时间。
最简单的方法可能是像这样发出 click in 元素(带有普通 HTML 表格的地方,子组件):
<template>
<table>
<tr>
<th @click="$emit('sort', {column: 'Name', isAsc: !isAsc})">Name</th>
<th> ... </th>
</tr>
</table>
</template>
props: {
isAsc: Boolean,
sortedBy: String
}
像这样的东西会被插入到父组件中:
<child-component-name @sort="sortTable" :sortedBy="sortedBy" :isAsc="isAsc" v-if="yourTableSummary"> ... </child-component-name>
components: {
'child-component-name': NameOfYourComponent
},
data() {
return {
isAsc: true,
sortedBy: 'Name'
yourTableSummary: {}
}
},
methods: {
sortTable({column, isAsc}) {
// Set isAsc to default if sorted column changes
if (column != this.sortedBy) {
isAsc = true
}
let sortedList = []
if (isAsc) {
sortedList =
this.yourTableSummary.Rows.sort((a, b) => {
return a[column].localeCompare(b[column])
})
} else {
sortedList =
this.yourTableSummary.Rows.sort((a, b) => {
return (a[column].localeCompare(b[column]) * -1 )
})
}
this.yourTableSummary.Rows = [...sortedList]
this.sortedBy = column
this.isAsc = isAsc
},
}
推荐阅读
- android - 在 FragmentPagerAdapter 中改造 GET
- jquery - JQGrid 按列排序仅在使用分页后有效
- c# - 无法使用 as 运算符或简单转换将列表转换或转换为另一个列表
- jquery-selectors - 在 Cypress 中优化选择器
- ffmpeg - ffmpeg 从顶部屏幕裁剪视频
- node.js - 使用 NodeJS 承诺在 DynamoDB 中创建记录
- html - 带有不可点击链接的轮播,而是点击上一个链接
- c++ - 对数字范围使用 boost
- python - 使用 selenium 遍历列表
- firebase - 删除和添加文档到 Firebase 时的时间问题