Vue v-if 即使满足条件也无法正常工作(Font Awesome 图标未更新)

Vue v-if not working even though condition is met (Font Awesome icon not updating)

在 VueJS 中,我有一个 table,其中包含可以排序的列。一次只能对一列进行排序。

排序前,按钮为fa-sort。排序后,按钮变为fa-arrow-up,再次点击按钮变为fa-arrow-down

当我对导入 Vue 库脚本的项目进行原型设计时,v-if 起作用了。但是在迁移到 Vue CLI 之后,这不起作用。

现在,如果我单击排序按钮,则会应用排序,但按钮图标不会改变。但是,如果我进入我的 Vue 工具并更改其中的 colBeingSorted 值,按钮图标 更新。

我尝试了很多事情:我将条件(或其变体)移动到计算中,然后移动到方法中。我还打印了 console.logged 数据以确认它是我所期望的。在所有情况下,我都可以确认满足条件,但由于某种原因图标没有更新。

有什么想法吗?建议?

我已经大大减少了代码示例,所以它不显示排序功能,只显示按钮图标格式。 sortedAscending 在正常工作的排序函数中更新:

<table>
  <thead>
    <tr>
      <th v-for="(column, prop) in header" :key="prop">
        <button-component
          v-if="colBeingSorted != prop"
          :icon="'fas fa-sort'"
          @click="colBeingSorted = prop"
        >
        <button-component
          v-else-if="colBeingSorted == prop && sortedAscending == true"
          :icon="'fas fa-arrow-up'"
        >
        <button-component
          v-else-if="colBeingSorted == prop && sortedAscending == false"
          :icon="'fas fa-arrow-down'"
        >
        {{ column }}
...
data() {
    return {
      colBeingSorted: -1,
    }
}

我不确定代码片段中为什么会发生这种情况,但我经常发现,如果您尝试保留相同的组件并更改道具,而不是让 if-else 具有不同的实例,事情会更好相同的组件。一种方法是只使用 1 个按钮组件:

<button-component
  :icon="getIcon(prop)"
  @click="handleClick(prop)"
/>

类似这样的方法

getIcon(prop) {
  if (this.colBeingSorted != prop) return 'fas fa-sort';
  if (sortedAscending) return 'fas fa-arrow-up';
  return 'fas fa-arrow-down';
},
handleClick(prop) {
  if (this.colBeingSorted == prop) {
    this.sortedAscending = !this.sortedAscending;
  } else {
    this.colBeingSorted = prop;
    this.sortedAscending = true;
  }
}

顺便说一句,我认为我没有看到 'prop' 在此处仅引用数组中的项目索引时被使用。当 prop 具有非常特殊的含义时,在 Vue 中尤其令人困惑!在这种情况下,我只使用 columnIndex。

感谢@Maylor,我实施了您的更改,虽然它本身并没有解决问题,但确实使我的代码更清晰,更易于调试。

经过更多调查,我发现问题不在我的 Vue 代码中,而是与 Font Awesome 有关。在后台,我的 button-component 使用 Font Awesome,即使值已更改,它也不会重新呈现图标。

之后,我删除了 fontawesome/js/all.js,现在只使用 fontawesome/css/all.css。这解决了问题。