8

I use Vue js conditional statements in multiple elements.

In some cases, i need to place if and else in same element to filter the elements.

Here,i use multiple elements to apply if and else.

   <block v-if="nb == 3" align="left"></block>
   <block v-if="nb > 3" align="center"></block>

But i want to apply both in single element like,

  <block v-if="nb == 3" align="left" v-else align="center"></block>

Is it possible ?

Or Any other solution to apply this ?

Thank in advance.

3 Answers 3

27

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.

Sign up to request clarification or add additional context in comments.

6 Comments

So Computed property is better than this "if and else"...?
@ShankarThiyagaraajan: I'd use a ternary expression for something this simple, but anything more would be much more readable put into a computed property. It's a stylistic choice though, do what feels right.
@ShankarThiyagaraajan: As far as I know, there's no way of using v-if and v-else on the same element, so I think binding to something is the only way.
v-if and v-else is for an entire element and not for an attribute, so this ternary seems like the bast way.
@StevenWade: I agree - while you could duplicate the element and use v-if/else, it'd make your markup more cluttered than it needs to be.
|
7

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'
    }
  }
}

Comments

0

You could simply achieve that with a ternary operator

<block :align="nb==3?'right':'left'"></block>

1 Comment

already exist as an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.