如何在一个 class vue.js 2 中添加 2 个条件?
How can I add 2 condition in one class vue.js 2?
我的vue组件是这样的:
<template>
<a :class="'btn ' + [respond == 'responseFound' ? ' btn-yellow' : ' btn-default', type == 1 ? ' btn-block' : ' btn-xs center-block']">
...
</a>
</template>
我这样试了,还是不行?
您可以使用 :class="[array, of, classes]"
语法:
<a :class="['btn', (respond === 'responseFound' ? 'btn-yellow' : 'btn-default'), (type === 1 ? 'btn-block' : 'btn-xs center-block')]">
作为奖励,您不必担心添加前导空格,Vue 会处理它。
只是为了在 view/template/markup 中保持整洁,将您的条件移至计算属性:
<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>
很确定当前显示的答案说明了如何在 1 个条件下添加多个 classes。但是如果你想为你的 class 添加多个条件,你可以简单地这样做:
:class="{classname: condition_one && condition_two}"
或者您可以这样做:
:class="[ condition1 | condition2 ? 'className' : '']"
这将检查任一条件是否为真。如果要检查两者,请将 |
替换为 &&
。但是,如果 else
class 中什么都没有,我认为 @Marnix 的回答更清晰。
我的vue组件是这样的:
<template>
<a :class="'btn ' + [respond == 'responseFound' ? ' btn-yellow' : ' btn-default', type == 1 ? ' btn-block' : ' btn-xs center-block']">
...
</a>
</template>
我这样试了,还是不行?
您可以使用 :class="[array, of, classes]"
语法:
<a :class="['btn', (respond === 'responseFound' ? 'btn-yellow' : 'btn-default'), (type === 1 ? 'btn-block' : 'btn-xs center-block')]">
作为奖励,您不必担心添加前导空格,Vue 会处理它。
只是为了在 view/template/markup 中保持整洁,将您的条件移至计算属性:
<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>
很确定当前显示的答案说明了如何在 1 个条件下添加多个 classes。但是如果你想为你的 class 添加多个条件,你可以简单地这样做:
:class="{classname: condition_one && condition_two}"
或者您可以这样做:
:class="[ condition1 | condition2 ? 'className' : '']"
这将检查任一条件是否为真。如果要检查两者,请将 |
替换为 &&
。但是,如果 else
class 中什么都没有,我认为 @Marnix 的回答更清晰。