使用vue 写出一个排序方法
时间: 2024-02-23 12:01:25 浏览: 28
可以使用Vue的计算属性来实现数组排序,实现方法如下:
```html
<template>
<div>
<button @click="sortBy('name')">按名称排序</button>
<button @click="sortBy('age')">按年龄排序</button>
<table>
<thead>
<tr>
<th>名称</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedList" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: '张三', age: 18 },
{ id: 2, name: '李四', age: 20 },
{ id: 3, name: '王五', age: 22 }
],
sortKey: '',
sortDesc: false
}
},
methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortDesc = !this.sortDesc
} else {
this.sortKey = key
this.sortDesc = false
}
}
},
computed: {
sortedList() {
const key = this.sortKey
const desc = this.sortDesc ? -1 : 1
return this.list.sort((a, b) => {
if (a[key] < b[key]) return -1 * desc
if (a[key] > b[key]) return 1 * desc
return 0
})
}
}
}
</script>
```
在上面的代码中,我们定义了一个 `list` 数组和 `sortKey`、`sortDesc` 两个变量用于绑定排序的状态。然后,我们使用 `sortBy` 方法来切换排序的状态,如果当前的排序键值和上一次相同,则切换排序方式,否则按升序排序。在计算属性 `sortedList` 中,我们根据排序键值和排序方式对数组进行排序,然后返回排序后的结果。在模板中,我们使用 `v-for` 指令循环渲染排序后的列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)