我正在尝试在 Vue 中创建一个可排序的表格组件并且一切正常,但我只是想添加一些小的收尾工作,我想要的一件事是向当前正在排序的列添加一个类并将其删除来自所有其他专栏,但我不知道如何做最后一部分。我一直在读一些东西说我不应该尝试以 Vue 中的 DOM 元素为目标,这让我也认为我对 event.target.classList.add()
的使用也不正确。
这是我目前的方法:
methods: {
sort_column (event, index) {
if (this.sortAsc) {
event.target.classList.add('sortable--down')
this.sortAsc = false
return this.tableData.sort((a, b) => {
if (a[index] < b[index]) return -1;
if (a[index] > b[index]) return 1;
return 0;
})
} else {
event.target.classList.add('sortable--up')
this.sortAsc = true
return this.tableData.sort((a, b) => {
if (a[index] > b[index]) return -1;
if (a[index] < b[index]) return 1;
return 0;
})
}
},
}
这就是它的名字:
<th v-for="(item, index) in headings" :key="index"
@click="sort_column($event, index)"">
回到 jQuery 的时代,我只会定位被点击元素的父级,找到所有列并从中删除类,但如果我不能(或不应该)定位 Vue 中的 DOM 元素,那么我对执行此操作的正确方法不知所措。
最佳答案
我唯一想到的就是像这样用 Vue 分配类(class)。 https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax
存储已排序的列的索引(在本例中名为 idxSorted
的变量中)然后执行(已测试):
<th :class="{ sorted: (index === idxSorted) }" v-for="(item, index) in headings" :key="index" @click="sort_column($event, index)"">
您可以通过对 sortAsc
的额外检查以相同的方式分配 sortable--down
和 sortable--up
类。
关于javascript - Vue 将类添加到目标但从其他实例中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56024364/