首页 > 解决方案 > 更新状态时Vue类绑定不起作用

问题描述

我正在尝试根据 v-for 中的索引进行 Vue 类绑定。我可以看到 Vue 开发工具中的状态正确更改,但类名没有更新。

<div class="group" v-for="(role, index) in roles_be">
  <span class="group-name"> {{ role.name }}</span>
  <i class="fas fa-info-circle"></i>
  <i class="fa fa-fw switch-icon" @click="toggleGroupElements(index)" v-bind:class="[ 
  groupElements.index ? 'fa-toggle-on' : 'fa-toggle-off' ]"></i>
</div>


groupElements: [false, false, false, false],


toggleGroupElements(index) {
              switch (index) {
                case 0:
                  this.groupElements[0] = !this.groupElements[0];
                  break;
                case 1:
                  this.groupElements[1] = !this.groupElements[1];
                  break;
                case 2:
                  this.groupElements[2] = !this.groupElements[2];
                  break;
                case 3:
                  this.groupElements[3] = !this.groupElements[3];
                  break;
              }

            },

标签: javascriptvue.js

解决方案


由于您尝试访问数组中的索引而不是对象中的键,因此您应该尝试groupElements[index]在类绑定中。

:class="[groupElements[index] ? 'fa-toggle-on' : 'fa-toggle-off' ]"

推荐阅读