vue3 列表渲染 排序
时间: 2023-07-23 08:04:25 浏览: 51
在 Vue3 中,你可以使用 `v-for` 指令来循环渲染列表,同时使用 `Array.sort()` 方法来对列表进行排序。
下面是一个基本的示例:
在模板中使用 `v-for` 指令来循环渲染列表,并使用 `Array.sort()` 方法对列表进行排序:
```html
<template>
<div>
<h2>Students List:</h2>
<ul>
<li v-for="student in sortedStudents" :key="student.id">
{{ student.name }} - {{ student.score }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
students: [
{ id: 1, name: "Tom", score: 90 },
{ id: 2, name: "Jerry", score: 80 },
{ id: 3, name: "Alice", score: 95 },
{ id: 4, name: "Bob", score: 85 },
],
};
},
computed: {
// 使用 computed 属性来定义一个计算属性 sortedStudents
// 在这个计算属性中,我们使用 Array.sort() 方法来按照分数(score)对学生列表进行排序
sortedStudents() {
return this.students.sort((a, b) => {
return b.score - a.score;
});
},
},
};
</script>
```
在上面的代码中,我们首先定义了一个包含学生信息的数据 `students`,然后使用 `computed` 属性来定义一个计算属性 `sortedStudents`,在这个计算属性中,我们使用 `Array.sort()` 方法来按照分数(`score`)对学生列表进行排序。最后,我们在模板中使用 `v-for` 指令来循环渲染排序后的学生列表。
注意事项:
- 在 Vue3 中,计算属性的定义方式与 Vue2 有所不同。需要使用 `computed` 属性来定义计算属性。
- 使用 `v-for` 循环渲染列表时,需要为每个列表项指定一个唯一的 `key` 属性,以提高列表渲染性能。在上面的示例中,我们使用 `:key="student.id"` 来为每个列表项指定一个唯一的 `id`。