How to add a condition to a class in vue.js 2?
My vue component looks like this:
<template>
<a href="javascript:" class="btn btn-block" :class="{ product == 'responseFound' ? ' btn-default' : ' btn-success' }" @click="add($event)">
...
</template>
There are errors:
invalid expression :: class = "{product == 'responseFound'? 'btn-default': 'btn-success'}"
How can I solve it?
+3
source to share
2 answers
Just remove the parentheses in :class
:
<template>
<a href="javascript:" class="btn btn-block" :class="product == 'responseFound' ? ' btn-default' : ' btn-success'" @click="add($event)">
...
</template>
If you want to add additional conditions, wrap it []
to create an array:
:class="[product == 'responseFound' ? ' btn-default' : ' btn-success', foo ? 'foo' : 'bar']"
+4
source to share
I would use a computed property for this behavior.
Which removes the logic from your template and moves it into your script part.
<template>
<a href="javascript:" class="btn btn-block" :class="classes" @click="add($event)">
</template>
<script>
export default {
computed: {
classes() {
return this.product == 'responseFound' ? 'btn-default' : 'btn-success'
}
}
}
</script>
+1
source to share