VueJs 条件付きでクリックイベントを listen する

Updated: 2020/9/2

 

APIを叩いてからボタンをクリックできるようにしたい等々

 

環境

Vue@2.6.12

 

<button @click="eventReady ? someFunc() : null">

 

computed: {

  eventReady() {

   if( // write condition ) {

     return true

   } else {

    return false

   }

  }

}

 

methods: {

  someFunc() {

 

  }

}

--------------------------------------------------------------------------------------

おまけ

三項演算子を使ったボタンのイベント条件分岐にさらに常時発火のメソッドを付加はできない。

<button @click="eventReady ? someFunc() : null & anotherFunc()">

 >>> cannot emit anotherFunc

 

ただし event modifier が必要である場合は可能

<button @click="eventReady ? someFunc() : null" @click.once="anotherFunc()">

>>> can emit anotherFunc

 

modifier が無いと click event の duplicate でエラー

<button @click="eventReady ? someFunc() : null" @click="anotherFunc()">

>>> error

 

modifier が必要ないイベントの場合、メソッドを一つにまとめてメソッド内で条件分岐を作る。

 

ref:

https://stackoverflow.com/questions/48042274/conditional-event-binding-vuejs

monteecristoo.hatenablog.com