Home > OS >  How to display icon in table headers when a column is sorted in vue
How to display icon in table headers when a column is sorted in vue

Time:07-12

I want to my table headers to have icon when that column is sort.

Up arrow when asc, Down arrow when desc.

This is the sample image that I want to get: enter image description here

Here's my table, and functions related:

<table id="table">
            <tr>
              <th style="text-align: center">
                <input
                  type="checkbox"
                  name="tableCheckBox"
                  v-model="allSelected"
                  @change="selectAll"
                />
              </th>
              <th style="text-align: right">#</th>
              <th
                v-for="head in table_headers"
                :key="head"
                @click.prevent="sort(head)"
              >
                <a
                  @click.prevent="sort(head)"
                  :
                >
                  {{
                    head == "NAME"
                      ? "Name"
                      : head == "program_name"
                      ? "Program"
                      : head == "iteration_name"
                      ? "Iteration"
                      : head == "stream_name"
                      ? "Stream"
                      : head == "group_name"
                      ? "Group"
                      : head
                  }}
                </a>
              </th>
            </tr>
            <tr
              v-for="(data, index) in sortedProperties"
              :key="data"
              :value="data"
              style="cursor: pointer"
            >
              <td >
                <input type="checkbox" v-model="selected" :value="data" />
              </td>
              <td style="text-align: right">{{ incrementIndex(index) }}</td>
              <td v-for="head in table_headers" :key="head">
                {{ data[head] }}
              </td>
            </tr>
         </table>


data: () => ({
     sortBy: "Name",
     sortDirection: 1,
}),

  methods: {
    sort(head) {
      this.sortBy = head;
      this.sortDirection *= -1;
    },

    sortMethods(head, direction) {
      return direction === 1
        ? (a, b) => (b[head] > a[head] ? -1 : a[head] > b[head] ? 1 : 0)
        : (a, b) => (a[head] > b[head] ? -1 : b[head] > a[head] ? 1 : 0);
    },
 },

computed: {
    sortedProperties() {
      const direction = this.sortDirection;
      const head = this.sortBy;
      return this.firstFetchUserData.sort(this.sortMethods(head, direction));
    },
}

CodePudding user response:

You can add the icon after a tag, and controls the display via sortBy and sortDirection.

<a
  @click.prevent="sort(head)"
  :
>
  {{...}}
</a>
<div  v-if="sortBy === head">
  <span v-if="sortDirection === 1">           
  • Related