如何在一个类vue.js 2中添加2个条件?

sam*_*toh 1 vue.js vue-component vuejs2

我的vue组件是这样的:

<template>
    <a :class="'btn ' + [respond == 'responseFound' ? ' btn-yellow' : ' btn-default', type == 1 ? ' btn-block' : ' btn-xs center-block']">
       ...
    </a>
</template>
Run Code Online (Sandbox Code Playgroud)

我尝试这样,但它不起作用?

Mat*_*att 10

你可以使用:class="[array, of, classes]"语法:

<a :class="['btn', (respond === 'responseFound' ? 'btn-yellow' : 'btn-default'), (type === 1 ? 'btn-block' : 'btn-xs center-block')]">
Run Code Online (Sandbox Code Playgroud)

作为奖励,您不必担心添加前导空格,Vue将处理它.


Sye*_*yed 9

只是为了保持视图/模板/标记中的内容干净,请将条件移至计算属性:

<template>
  <a :class="['btn', getRespondClass, getTypeClass]">
</template>

<script>
  export default {
    data () {
      return {
        respond: '',
        type: ''
      }
    },
    computed: {
      getRespondClass () {
        return this.respond === 'responseFound' ? 'btn-yellow' : 'btn-default'
      },
      getTypeClass () {
        return this.type === 1 ? 'btn-block' : 'btn-xs center-block'
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)