javascript - VueJS 2 中的排序

标签 javascript arrays sorting vuejs2

我尝试使用 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);
      }

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

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

最佳答案

你的问题与Vue没有任何关系。 JavaScript 中数组排序的工作方式与您的预期不同。您无法将键传递给 sort();相反,您必须实现自己的比较函数:

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

排序也可以就地进行,因此不需要复制和重新分配数组。

关于javascript - VueJS 2 中的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40405662/

相关文章:

c++ - boost circular_buffer 或堆排序性能

javascript - 如何将 setState 设置为新对象?

javascript - 尝试连接 MongoDB Atlas 时如何修复密码错误?

java - 如何通过仅在数组中引用来使对象为空?

在 C 函数中创建数组

arrays - SWIFT - 无法将类型 '[(String, [String : Any])]' 的值分配给类型 '[String : [String : Any]]'

c++ - sort() - 没有匹配函数来调用 'swap'

javascript - 从 JS 迁移,tsc 构建中的错误

javascript - 将函数绑定(bind)到窗口调整大小和窗口滚动,但也立即调用它

git - 如何对 git 分支输出进行版本排序(与通常的字母/字典排序相比)