首页 > 解决方案 > 排序表不起作用Vue

问题描述

我找到了这支笔https://codepen.io/cfjedimaster/pen/BYpJgj但它在我的实现中不起作用。我不明白我做错了什么

<table>
  <thead>
    <tr class="header">
      <th @click="sort('campaign')">Campaign</th> // click heandler
      <th @click="sort('time')">Time</th>
      <th @click="sort('views')">Views</th>
      <th @click="sort('visitors')">Visitors</th>
      <th @click="sort('ctr')">CTR</th>
      <th @click="sort('cpc')">CPC</th>
      <th @click="sort('cpv')">CPV</th>
      <th @click="sort('cpm')">CPM</th>
      <th @click="sort('status')">Status</th>
   </tr>
 </thead>
   <tbody> //target table
     <tr v-for="item in data" :key="item.id"> // loop
       <td>{{item.name}}</td> //row
       <td>{{item.time}}</td>
       <td>{{item.views}}</td>
       <td>{{item.visitors}}</td>
       <td>{{item.ctr}}</td>
       <td>{{item.cpc}}</td>
       <td>{{item.cpv}}</td>
       <td>{{item.cpm}}</td>
       <td>{{item.status}}</td>
     </tr>
   </tbody>
</table>

data(){
 return{
   data: [], // data
     currentSort:'campaign', // dynamic property
     currentSortDir:'asc'
   }
},
methods:{ // methods
  getData(){
    this.data = this.$store.state.graphArr // get data from store
  },
  sort(s) { // sort function
    //if s == current sort, reverse
    if(s === this.currentSort) { // if statement
      this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';                  }
      this.currentSort = s; // setting currentSortDir
    }
      },
computed:{ // computed
  sortedCats() { // where this function should be called
    return this.data.sort((a,b) => { // ES Lint highlits "this". Unexpetced side effect
      let modifier = 1;
      if(this.currentSortDir === 'desc') modifier = -1;
      if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
      if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
        return 0;
    });
  }
}

也许我应该在某个地方调用 sortedCats 函数?在这种情况下,计算属性的作用是什么?

标签: vue.jsvuejs2

解决方案


您需要遍历sortedCats数组以获得所需的结果,而不是每次通过属性单击排序data时返回新值。sortedCatscomputed

<tr v-for="item in sortedCats" :key="item.id">

推荐阅读