【问题标题】:Vue add class to target but remove from other instancesVue将类添加到目标但从其他实例中删除
【发布时间】:2019-05-07 14:01:03
【问题描述】:

我正在尝试在 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 元素,那么我不知道该怎么做。

【问题讨论】:

  • 嗨,除了这个问题,你试过vuetifyjs.com/en吗?他们有一个非常好的表格实现

标签: javascript vue.js


【解决方案1】:

我唯一想到的就是像这样用 Vue 分配课程。 https://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)"">

您可以以相同的方式分配sortable--down 和sortable--up 类,并额外检查sortAsc。

【讨论】:

  • 完美。谢谢,我有一种感觉,我最终需要做一些我看不到的简单得令人沮丧的事情:)
猜你喜欢
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
相关资源
最近更新 更多