vue.js - 排序表不起作用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 函数?在这种情况下,计算属性的作用是什么?
解决方案
您需要遍历sortedCats
数组以获得所需的结果,而不是每次通过属性单击排序data
时返回新值。sortedCats
computed
<tr v-for="item in sortedCats" :key="item.id">
推荐阅读
- git - 有什么简单快速的方法来判断一个 git repo 是否使用了 LFS
- python - 破碎方程求解器
- python - 创建一个函数来检查一个数 n 是否可以被两个数 x 和 y 整除。所有输入都是正数,非零数字
- ios - 如何将 ARPlaneAnchor 转换为 2d 线(平行投影)
- javascript - Javascript Map 函数未存储正确的值
- r - 如何在R中重置为0的cumsum?
- react-native - 从 flatlist 切换到 Listitem 并检索数据
- python - AttributeError:模块“cv2.cv2”没有属性“nameWindow”
- ios - iOS swift URLScheme 静默发布,无需打开另一个应用程序
- typescript - 如何使用 Array.map 将打字稿元组映射到新元组