Can I make it so a click event only executes if a certain variable is true?

611 views Asked by At

I want to make it so that a user can only trigger an on click event and then execute a function only if a certain variable is true. For example:

<button @click='hello'>Trigger</button>

data: function() {
    return {
        isAuth: true
    }
},
methods: {
    hello(){
         console.log('hello')
    }
}

I just want to point out that I don't want to only hide the button. I want to make clicks on the button element not trigger unless isAuth: true.

2

There are 2 answers

0
aprouja1 On
<button @click='hello'>Trigger</button>
data: function() {
return {
  isAuth: true
 }
},
methods: {
 hello() {
  if (this.isAuth) {
    console.log('hello')
  }
 }
}
0
waleed ali On

I guess you can do the following way, if you really want:

<button @click='isAuth ? hello : {}'>Trigger</button>

but honestly, this, to me, is not the right way. and I think you should consider calling the function on button click and inside that function, you can use an if statement:

<button @click='hello'>Trigger</button>

data: function() {
    return {
        isAuth: true
    }
},
methods: {
    hello(){
      if (!this.isAuth) return;
      console.log('hello')
    }
}