近期在為專案添加新功能時,要能讓某個按鍵(功能)在某些條件下不執行,

原先我的作法 (程式碼一) 是在 methods 之中多增加條件判斷,讓程式不執行避免報錯。

但是這功能本身就會用到 if else 了,所以這樣的作法讓整個 function 看起來有點亂。

程式碼一 :

findTextLiveIndex(el) {
      let index = 0
      if (el.target.dataset.quarter == 2) {
        index = this.playList.findIndex((e) => e.current_num === 1)
        if (index == -1) {
          return
        } else {
          this.$refs.mySwiper.swiper.slideTo(index, 500)
        }
      } else if (el.target.dataset.quarter == 3) {
        index = this.playList.findIndex((e) => e.current_num === 2)
        if (index == -1) {
          return
        } else {
          this.$refs.mySwiper.swiper.slideTo(index, 500)
        }
      } else if (el.target.dataset.quarter == 4) {
        index = this.playList.findIndex((e) => e.current_num === 3)
        if (index == -1) {
          return
        } else {
          this.$refs.mySwiper.swiper.slideTo(index, 500)
        }
      }
    },

寫完之後我自己看的也是不太舒服啦,所以就想著如何改善。😅

後來就覺得只要讓對應的 HTML 按鈕在需要的條件下再綁定 on-click 也行,

第一個想到的方法就是 V-if 與 V-else 切換 HTML按鈕。

但這邊又衍生出另一個問題了,原先的HTML (程式碼二)中就已經使用到 V-if 與 V-else 。

這樣勢必要再改動 HTML 的結構,實在有點費工。

程式碼二 :

<span
  v-if="condition <= 4"
  :class="[condition === 4 ? 'live' : 'notYet']"
	@click="findTextLiveIndex"
  data-quarter="4"
	>第一、二種狀態</span
>

<span 
	class="over" 
	v-else 
	@click="findTextLiveIndex" 
	data-quarter="4"
	>第三種狀態</span
>

最後讓我尋找到另一種解法,也就是直接讓 V-on 增加條件判斷。

基本的寫法就是像程式碼三這樣,& 前面是條件判斷,& 後面就是要綁定的 function

程式碼三 :

@click="condition === 3 && functionName()"

如果像我需要取得 DOM Target 時則可以傳入$event 取得被點擊的DOM。

程式碼四 :