【问题标题】:vueJS sort nesting table rowsvueJS对嵌套表行进行排序
【发布时间】:2021-03-06 09:24:24
【问题描述】:

我有一个像这样的 json 对象列表(运营商):

在我的 *.vue 中,我使用:

<tr v-for="carrier in this.carriers">
   <td>{{ carrier.id }}</td> ....

可以点击我的thead/th's对表格进行排序,如下所示:

<thead>
   <tr>
      <th class="pointer link" @click="sort('id')">
         ID
         <span v-if="'id' === currentSortCol">
            {{currentSortDir ==='asc' ? '&#8593;':'&#8595;'}}
         </span>
      </th>
      <th class="pointer link" @click="sort('region.name')">
         Region
         <span v-if="'region.name' === currentSortCol">
            {{currentSortDir ==='asc' ? '&#8593;':'&#8595;'}}
         </span>
      </th>....

而我的排序方法是这样的:

        sort(col) {
            if (this.currentSortCol === col) {
                this.currentSortDir = this.currentSortDir === "asc" ? "desc" : "asc";
            } else {
                this.currentSortCol = col;
            }
            this.carriers.sort(this.sortBy(col, this.currentSortDir));
        },
        sortBy(property, order) {
            this.currnetSortDir=order;
            return function(a, b) {
                const varA =
                    typeof a[property] === "string"
                        ? a[property].toUpperCase()
                        : a[property];
                const varB =
                    typeof b[property] === "string"
                        ? b[property].toUpperCase()
                        : b[property];

                let comparison = 0;
                if (varA > varB) comparison = 1;
                else if (varA < varB) comparison = -1;
                return order === "desc" ? comparison * -1 : comparison;
            };
        }

问题: 使用 ID (carrier.id) 排序 asc, desc 很好。但它不会对嵌套的carrier.region.name 列进行排序。 如何对嵌套列进行排序,例如这个 carrier.region.name?

【问题讨论】:

    标签: javascript html vue.js


    【解决方案1】:

    你应该使用类似 lodash 包中的 'get' 方法来获取嵌套道具:

    import _get from 'lodash/get'
    ...
    const propValueA = _get(a, property);
    const propValueB = _get(b, property);
    const varA = typeof propValueA === "string" ? propValueA.toUpperCase() : propValueA;
    const varB = typeof propValueB === "string" ? propValueB.toUpperCase() : propValueB;
    

    【讨论】:

    • const propValueA = _get(a, property);常量 propValueB = _get(b, 属性); const varA = typeof propValueA === "string" ? propValueA.toUpperCase() : propValueA; const varB = typeof propValueB === "string" ? propValueB.toUpperCase() : propValueB; - 将工作。你能更新你的答案,然后我会接受它
    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2019-06-25
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多