11

This is my for loop:

  <li v-for="(crumb, index) in breadcrumbs" :class="{ 'is-active' : index==breadcrumbs.length-1 }">
    <a href="javascript:void(0)" v-if="index==breadcrumbs.length-1">{{ crumb.name }}</a>
  </li>

@click="methodName" shouldn't be available for the last iteration.

I can check the last iteration with index==breadcrumbs.length-1 Is this possible using apply v-if?

1
  • 1
    Just bind the @click handler as usual, but in the callback simply check if the item is the last item. If it is the last item, return false or just do event.preventDefault(). Commented Dec 12, 2018 at 12:00

3 Answers 3

39

There is a possibility by defining the event handler this way:

v-on="condition ? { eventName: () => handler } : {}"

The ?: operator can be used as a shortcut for an if...else statement

In your case it would be like this:

<li v-for="(crumb, index) in breadcrumbs" :class="{ 'is-active' : index==breadcrumbs.length-1 }">
    <a href="javascript:void(0)" v-on="index < breadcrumbs.length-1 ? { click: () => methodName(parms) } : {click: ($event) => $event.preventDefault() }" >{{ crumb.name }}</a>
</li>

Small fiddle

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

Comments

1
@click="someBooleanVariable ? console.log('yes') : {}"

Comments

0

Just another way to handle conditional @click, especially if we have multiple cases

We call the method

v-on="myMethod(breadcrumbs.length, index)"

and inside the method we do handle the conditional

myMethod(let length, let index){
  if (index == 0){
    this.myMethod1()
  } 
else if (index == length-1){
  this.myMethod2()
}

Comments

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.