vue.js - 使用 VueJS 对对象数组中的标题进行排序
问题描述
我正在尝试对我的对象数组进行排序。我已经设法使用控制台返回所有标题,但现在正在努力执行实际排序。我正在使用选择菜单在相关性(默认)和按字母顺序排序之间切换。
任何帮助是极大的赞赏
<select v-model="sortatoz" v-on:change="sortItems($event)">
<option disabled value="">Select</option>
<option value="alphabetically">Alphabetically</option>
<option value="relevance">Relevance</option>
</select>
methods: {
sortItems: function sortItems(event) {
this.sortby = event.target.value;
if (this.sortatoz === "alphabetically") {
Array.from(
document.querySelectorAll("div > h3.title")
).map((x) => x.innerText);
??What should I add here to sort???
} else {
Array.from(
document.querySelectorAll("div > h3.title")
).map((x) => x.innerText);
???
}
},
解决方案
第 1 步:创建选项HTML
模板使用排序功能显示数据。select
table
<div id="app">
<select v-model="sortatoz" @change="sortItems">
<option disabled value="">Select</option>
<option value="alphabetically">Alphabetically</option>
<option value="relevance">Relevance</option>
</select>
<table border="1">
<thead>
<tr>
<th>Title</th>
<th>Authur</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in sortedItems" :key="index">
<td>{{ item.title }}</td>
<td>{{ item.authur }}</td>
</tr>
</tbody>
</table>
</div>
第 2 步:定义model
数据。我创建了一个带有名称data
的书籍title
Authur
data() {
return {
sortatoz: "",
listTitles: [
{
title: "Cabbages and Kings",
authur: "O. Henry",
},
{
title: "Alien Corn",
authur: "Sidney Howard",
},
{
title: "The Little Foxes",
authur: "Lillian Hellman",
},
{
title: "A Time of Gifts",
authur: "Patrick Leigh Fermor",
},
{
title: "Ego Dominus Tuus",
authur: "W. B. Yeats",
},
{
title: "Antic Hay",
authur: "Aldous Huxley",
},
],
};
},
第 3 步:定义您的computed
生命周期。当数据发生变化时,model
自动computed
功能将得到更新。
computed: {
sortedItems() {
return this.listTitles;
},
},
第 4 步:为选项定义@change
事件select
methods: {
sortItems() {
if (this.sortatoz === "alphabetically") {
return this.listTitles.sort((a, b) => (a.title > b.title ? 1 : -1));
} else {
return this.listTitles.sort((a, b) => (a.title > b.title ? -1 : 1));
}
},
},
推荐阅读
- scala - 如何使用特定版本的 scala 安装特定版本的 spark
- reactjs - 在 reactjs 中添加字体 css
- python - 如果块没有触发,即使它应该触发
- c++ - 在线程之间共享一个类
- c# - 如何使用角色在 webApi 中进行过滤
- wpf - 将图像控件绑定到数据网格数据上下文(视图模型)
- php - 谁能帮我在 Yii2 框架中将多个数组保存到数据库中?
- r - 在 Cox 回归中获得零 P 值:R
- python - 在python中解析列表的子列表
- c++ - cmake 错误 [SDK/Util/CMakeLists.txt:132 (add_library) 处的 CMake 错误]