Vuejs 类绑定和类插值

a--*_*--m 3 javascript vue.js

在视图中我需要生成以下类:

<div class="comp comp--lock comp--red">Foo</div>
Run Code Online (Sandbox Code Playgroud)

lock基于red状态,其中可能有以下颜色值:

  • comp--redcomp--yellowcomp--blue和许多其他可能的颜色

到目前为止,我一直在使用计算方法根据数据连接类名:

getCompClassName(){
  return `comp ${this.isLock ? 'comp--lock' : ''} comp--${this.color}`
}
Run Code Online (Sandbox Code Playgroud)

查看 Vuejs 文档,我发现应该以v-bind:class更好的方式解决这个问题,我遇到的问题是如何解决插值color,因为我需要声明所有可能的颜色。

data: {
  classObject: {
    'comp--lock': this.isLock,
    'comp--red': this.color === 'red',
    'comp--blue': this.color === 'blue',
    'comp--yellow': this.color === 'yellow'
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以使用v-bind:class更好的扩展来解决这个问题,而不必列出所有可能性,或者我应该使用计算方法来插入类名?

Tuq*_*ain 5

你不能只使用计算的吗?

computed: {
  classObject() {
    return {
      'comp--lock': this.isLock,
      [`comp--${this.color}`]: true
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

JSfiddle:https://jsfiddle.net/5sknyauz/5/

编辑:你实际上可以在数据中做同样的事情:

data() {
  return {
    classObject: {
      'comp--lock': this.isLock,
      [`comp--${this.color}`]: true
    }
  }
}
Run Code Online (Sandbox Code Playgroud)