首页 > 解决方案 > 在 Vue.js 中连接多个类

问题描述

我想用更少的代码编写一个函数,该函数将添加活动类名并自动删除所有其他活动类名。但就我而言,JavaScript 还需要一个唯一的类名。但是想把这一切都放在类名中。我怎样才能使它成为一个有效的类名。有没有办法做到这一点,所以它不会相互冲突。

    <ul class="three">
      <li 
        v-for="(post, index) in listData.data" 
        :key="index" 
        :class="'list-item unordered-list ' + post.name.toLowerCase() +  { active : activeName == post.name}" 
         @click="showInfo(post.name, post.description)">
        {{ post.name }}
      </li>
    </ul>

标签: classvue.js

解决方案


查看类绑定的对象语法或数组语法,它允许绑定到由值返回的对象或数组。这样,您可以通过从模板调用函数来简化复杂的类或样式组合,例如文档中的示例:

<div v-bind:class="classObject"></div>
...
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

推荐阅读