【问题标题】:Vue v-if not working even though condition is met (Font Awesome icon not updating)即使满足条件,Vue v-if 也不起作用(Font Awesome 图标未更新)
【发布时间】:2021-08-07 02:37:44
【问题描述】:

在 VueJS 中,我有一个包含可以排序的列的表。一次只能排序一列。

排序前,按钮为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,
    }
}

【问题讨论】:

    标签: vue.js font-awesome vue-cli


    【解决方案1】:

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

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

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

    【讨论】:

    • 听起来不错 - 祝你的项目好运
    【解决方案2】:

    我不确定为什么代码 sn-p 会发生这种情况,但我经常发现如果你尝试保持相同的组件并更改道具,而不是使用不同的 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2019-08-09
      • 2019-04-05
      • 2017-12-25
      • 2023-02-01
      • 2021-06-19
      相关资源
      最近更新 更多