首页 > 解决方案 > 使用 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);
            ???
          }
        },

标签: vue.js

解决方案


第 1 步:创建选项HTML模板使用排序功能显示数据。selecttable

 <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));
    }
  },
},

演示


推荐阅读