首页 > 解决方案 > Vue排序表(从高到低排序)

问题描述

嗨,我是 vuejs 的新手。我想按从最高到最低对表格进行排序。但是我安装了 vue-sorted-table 库。但是当我尝试运行代码时,数据总是从最低到最高返回。谁能帮我?谢谢..

这是代码:

<template>
  <div id="app">
    <sorted-table :values="values" @sort-table="onSort">
      <thead>
        <tr>
          <th scope="col" style="text-align: left; width: 10rem;">
            <sort-link name="id">ID</sort-link>
          </th>
        </tr>
      </thead>
      <template #body="sort">
        <tbody>
          <tr v-for="value in sort.values" :key="value.id">
            <td>{{ value.id }}</td>
          </tr>
        </tbody>
      </template>
    </sorted-table>
  </div>
</template>

<script>
import { ChevronUpIcon } from "vue-feather-icons";

export default {
  name: "App",
  data: function() {
    return {
      values: [{ id: 2 }, { id: 1 }, { id: 3 }],
      sortBy: "",
      sortDir: ""
    };
  },
  components: {
    ChevronUpIcon
  },
  methods: {
    onSort(sortBy, sortDir) {
      this.sortBy = sortBy;
      this.sortDir = sortDir;
    }
  }
};
</script>

<style>
.feather {
  transition: 0.3s transform ease-in-out;
}

.feather.asc {
  transform: rotate(-180deg);
}
</style>

代码可以在这里访问:

https://codesandbox.io/s/pedantic-kirch-bx9zv

标签: vue.jsvuejs2vue-tables-2vuejs3

解决方案


dir属性添加到sorted-table,并使其值等于desc

<template>
  <div id="app">
    <sorted-table :values="values" @sort-table="onSort" dir="desc">
      <thead>
        <tr>
          <th scope="col" style="text-align: left; width: 10rem;">
            <sort-link name="id">ID</sort-link>
          </th>
        </tr>
      </thead>
      <template #body="sort">
        <tbody>
          <tr v-for="value in sort.values" :key="value.id">
            <td>{{ value.id }}</td>
          </tr>
        </tbody>
      </template>
    </sorted-table>
  </div>
</template>

<script>
import { ChevronUpIcon } from "vue-feather-icons";

export default {
  name: "App",
  data: function() {
    return {
      values: [{ id: 2 }, { id: 1 }, { id: 3 }],
      sortBy: "",
      sortDir: ""
    };
  },
  components: {
    ChevronUpIcon
  },
  methods: {
    onSort(sortBy, sortDir) {
      this.sortBy = sortBy;
      this.sortDir = sortDir;
    }
  }
};
</script>

<style>
.feather {
  transition: 0.3s transform ease-in-out;
}

.feather.asc {
  transform: rotate(-180deg);
}
</style>

检查https://github.com/BernhardtD/vue-sorted-table并注意dir表的属性,你会找到答案


推荐阅读