首页 > 解决方案 > 如何根据计算属性显示排序图标?

问题描述

我想根据计算值显示相应的排序图标。例如,如果单击了 column1,则 classRefcodeDown 或 classRefcodeUp 为 true。两个计算属性都调用一个 sortClassRefcode 方法,该方法的值将使用 filterOptions.sort_by(refcode、column2、column3 等...)和 filterOptions.sort_type('ASC' 或 'DESC')进行评估。但不能相应地工作。请。检查我的 HTML 下面的代码:

<div v-if="classRefcodeDown"> 
      <i class="fas fa-sort-down"></i>
  </div>
  <div v-else-if="classRefcodeUp"> 
      <i class="fas fa-sort-up"></i>
  </div>
  <div v-else> <i class="fas fa-sort"></i> 
</div>

vuejs 计算

computed: {          
    classRefcodeUp: function(){
        return this.sortClassRefcode('refcode', 'ASC')
    },
    classRefcodeDown: function(){
        return this.sortClassRefcode('refcode', 'DESC')
    }
}

Vue.js 方法

methods: {
  sortClassRefcode: function(field, type) {
      if(this.filterOptions.sort_by == field && this.filterOptions.sort_type == type){
          return true
      }
      return false
  }
}

当我运行这些计算属性时,计算的属性会相应地发生变化,但出现的图标并不反映基于计算值

开发工具计算

开发工具计算

意外输出图标

意外输出图标

标签: vue.jsvue-directives

解决方案


Your computed properties have no actual dependencies. At the simplest level, the dependencies of a computed property are any direct accesses to a value in the data property, or to another computed property.

A computed property will only re-evaluate when some of its reactive dependencies have changed.

Both of your computed properties call a method without accessing either type of value, therefore a change will never be identified.

If you want it to react to changes, check this.filterOptions.sortyBy and this.filterOptions.sort_type in the computed property.


There's still an easier way to handle this though. Why not just use a single computed property to get the icon, and use that as the class description?

computed: {
    refCodeClass() {
        if (this.filterOptions.sort_by === 'refcode') {
            return this.filterOptions.sort_type === 'ASC' 
                ? 'fa-sort-up' 
                : 'fa-sort-down';
        }
        return 'fas-sort''
    }
}
<i class="fas" :class="refCodeClass"></i>

推荐阅读