Conditional @click with a method in vuejs
Asked Answered
T

3

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?

Tangy answered 12/12, 2018 at 11:57 Comment(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().Oneupmanship
A
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

Aircool answered 12/12, 2018 at 12:13 Comment(0)
R
1
@click="someBooleanVariable ? console.log('yes') : {}"
Remake answered 6/6, 2023 at 11:2 Comment(0)
N
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()
}
Neurovascular answered 14/5, 2024 at 6:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.