2

我正在尝试使用 slice().sort() 对 VueJS 2 中的项目列表进行排序,但它没有任何效果。在 vuejs 1 中有一个不错的 orderBy 过滤器,但他们删除了它。我目前的设置如下:

<table>
        <thead>
          <tr>
            <th v-for="column in columns" v-on:click="sortBy(column)">{{ column }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="customer in customerslist">
            <td>{{ customer.firstname }}</td>
            <td>{{ customer.surname }}</td>
            <td>{{ customer.added }}</td>
            <td></td>
          </tr>
        </tbody>
      </table>

...

      sortBy(sortKey) {
        this.customerslist = this.customerslist.slice().sort(sortKey);
        console.log(sortKey);
        console.log(this.customerslist[0].firstname);
      }

这是一个包含客户的二维数组。每个客户都有一个名字、姓氏和添加的字段。

但是,如果我单击名字列标题,这总是在控制台中返回相同的名字(虽然这不是按字母顺序正确的标题)。排序是如何工作的,因为我找不到正确的文档。

4

1 回答 1

4

您的问题与 Vue 无关。JavaScript 中的数组排序与您预期的不同。您不能将密钥传递给sort(); 相反,您必须实现自己的比较功能:

this.customerslist.sort((a, b) => a[sortKey].localeCompare(b[sortKey]));

排序也可以就地工作,因此不必复制和重新分配数组。

于 2016-11-11T22:54:15.457 回答