How to use "v-if" and "v-else" in same tag in HTML using Vue JS?
Rather than using v-if
, try binding the attribute to a ternary expression.
// : is a shorthand for v-bind:
<block :align="nb == 3 ? 'left' : 'center'"></block>
If that looks a little too messy for you (or if the logic you want to use is too complicated to express in a single line), you could also try creating a computed property in your component that returns "left"
or "center"
, and then bind to that instead.
You can't use v-if
and v-else
on the same element.
I'd personally use a computed property.
I'm assuming your nb
is a reactive variable or similar.
Therefore you should be looking for something like this:
<block v-bind:align="computedAlign"></block>
and then in your component
// assuming you're using data and not props
data() {
return {
nb: 1 // default
}
},
// some other stuff that sets the nb variable in some way
computed: {
computedAlign() => {
if (this.nb === 3) {
return 'left'
} else {
return 'center'
}
}
}