1. 程式人生 > 實用技巧 >Vue -- element-ui 所有資料前臺排序

Vue -- element-ui 所有資料前臺排序

<el-table
  v-loading="loading"
  :data="tableData.slice((pageNum-1)*pageSize,pageNum*pageSize)"
  style="width: 100%;"
  @sort-change="sort_change"
>
  <el-table-column :label="$t('table.date')" align="center" prop="recordDate" sortable>
    <template slot-scope="scope">
      <span>{{ parseTime(new Date(scope.row.recordDate), "{y}-{m}-{d}") }}</span>
    </template>
  </el-table-column>
  <el-table-column label="新增人數" align="center" prop="followNum" sortable />
  <el-table-column label="取消關注人數" align="center" prop="unFollowNum" sortable />
  <el-table-column label="淨增人數" align="center" prop="increaseNum" sortable />
  <el-table-column label="累積人數" align="center" prop="currdateFollowNum" sortable />
</el-table>
<pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" />
data(){
      return {
            loading: true,
            pageNum: 1,
            pageSize: 10, 
            total: 4,
            tableData: []
      }
},
methods: {
  sort_change(column) { // column是個形參,具體檢視element-ui文件
      // console.log(column)
      this.pageNum = 1 // return to the first page after sorting
      if (column.prop === 'recordDate') {
          this.tableData = this.tableData.sort(this.sortFun(column.prop, column.order === 'ascending'));
          // console.log(this.tableData);
      } else if (column.prop === 'followNum') {
          this.tableData = this.tableData.sort(this.sortFun(column.prop, column.order === 'ascending'));
          // console.log(this.tableData);
      }else if (column.prop === 'unFollowNum') {
          this.tableData = this.tableData.sort(this.sortFun(column.prop, column.order === 'ascending'));
          // console.log(this.tableData);
      }else if(column.prop === 'currdateFollowNum') {
        this.tableData = this.tableData.sort(this.sortFun(column.prop, column.order === 'ascending'));
          // console.log(this.tableData);
      }
      // this.showed_data = this.tableData.slice(0, this.pageSize) // 排序完顯示到第一頁
      console.log('Finished')
    },
    sortFun: function (attr, rev) {
      //第一個引數傳入info裡的prop表示排的是哪一列,第二個引數是升還是降排序
      if (rev == undefined) {
          rev = 1;
      } else {
          rev = (rev) ? 1 : -1;
      }
      return function (a, b) {
          a = a[attr];
          b = b[attr];
          if (a < b) {
              return rev * -1;
          }
          if (a > b) {
              return rev * 1;
          }
          return 0;
      }
    },
}

特別感謝那篇文章,給人家點了贊忘記留連結了,所以沒留原文連結,再次感謝!