我正在嘗試對我的物件陣列進行排序。我已經設法使用控制臺回傳所有標題,但現在正在努力執行實際排序。我正在使用選擇選單在相關性(默認)和按字母順序排序之間切換。
任何幫助是極大的贊賞
<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);
???
}
},
uj5u.com熱心網友回復:
第 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書籍的示例模??型titleAuthur
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));
}
},
},
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/348564.html
標籤:Vue.js
下一篇:檢查元素是否在x秒前創建
