A
A
Anton89892020-07-20 11:37:21
Vue.js
Anton8989, 2020-07-20 11:37:21

How to sort table by button?

Good afternoon) There is a table in Vuetify. It is necessary that sorting by the field in the table is carried out by a separate button outside the table. Now sorting is implemented in a standard way
(when clicking on the header), you need to repeat the algorithm so that the same sorting by field occurs only when you click on a separate button. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-01-04
@Anton8989

data: () => ({
  sortBy: '',
  ...
}),

<v-btn @click="sortBy = 'имя_свойства_по_которому_надо_выполнить_сортировку'">click me</v-btn>

<v-data-table :sort-by.sync="sortBy">...</v-data-table>

If you need to switch the sort order when you click again, then like this:
data: () => ({
  sortBy: [],
  sortDesc: [],
  ...
}),
methods: {
  sort(colName) {
    const sameCol = this.sortBy[0] === colName;
    const sortDesc = this.sortDesc[0];

    this.sortBy = sameCol && sortDesc ? [] : [ colName ];
    this.sortDesc = sameCol && sortDesc ? [] : [ sameCol ];
  },
  ...
},

<v-btn @click="sort('имя_свойства_по_которому_надо_выполнить_сортировку')">click me</v-btn>

<v-data-table :sort-by.sync="sortBy" :sort-desc.sync="sortDesc">...</v-data-table>

In the case of sorting by several properties, the sort method will look like this:
sort(colName) {
  const index = this.sortBy.indexOf(colName);
  if (index === -1) {
    this.sortBy.push(colName);
    this.sortDesc.push(false);
  } else if (this.sortDesc[index]) {
    this.sortBy.splice(index, 1);
    this.sortDesc.splice(index, 1);
  } else {
    this.$set(this.sortDesc, index, true);
  }
},

In general, it can be done quite simply. A click on the header of the specified column is simulated, then the table component will perform everything in the best possible way:
<v-btn @click="sort('имя_свойства_по_которому_надо_выполнить_сортировку')">click me</v-btn>

<v-data-table ref="table">...</v-data-table>

methods: {
  sort(colName) {
    const index = this.свойство_описывающее_столбцы_таблицы.findIndex(n => n.value === colName);
    this.$refs.table.$el.querySelector('thead tr').cells[index].click();
  },
  ...
},

D
Dima Pautov, 2020-07-20
@bootd

Just take the data, create a computed property (computed) specify it for the table, create a flag (boolean to indicate whether it is sorted or not), change the flag on a button click. Well, in the calculated property based on the flag, output a standard array or sorted using the sort method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question