超簡單學習 Vue.js 系列 | 多元按鈕 Vue Multiway Buttons


  1. 多元按鈕 Vue Multiway Buttons

Vue.js 簡單的示範專案,使用 Vue CLI 實作將所學習的知識以及實作需要的功能,藉此將知識實際結合,記得牢、想得到、用得出來。本次示範 Event Listener 以及 Click Modifier 的使用方式。

logo

多元按鈕 Vue Multiway Buttons

技術關鍵字 說明
Click Modifier 控制 Element 結合各種組合 Click 的呼叫事件
Dynamic Classes 根據 Vue Data 動態判斷使用指定 Class 與否於 Element 上

設計的重點在於 Button 使用 Click Modifier,來對應配合不同的系統鍵如 Shift, Alt, Ctrl 對應到不同的方法使用,其中 Meta 是指作業系統鍵,在微軟生態系為視窗鍵,蘋果生態系則為 ⌘ Command 鍵。

在配合互動的 Div Element 上,使用 Dynamic Class 的方式,判斷 Data 中的 ClickStyle 內容來決定所使用的 Class 項目。

<div class="btn btn-primary" 
  @click.exact="clickIt('Pure')" 
  @click.alt="clickIt('Alt')"
  @click.ctrl="clickIt('Control')"
  @click.meta="clickIt('Windows')"
  @click.shift="clickIt('Shift')"> Click</div>

<div class="responseBox text-dark mt-5 p-4"
  :class="{ 
    'bg-danger': clickStyle === 'Alt',
    'bg-primary': clickStyle === 'Control',
    'bg-white': clickStyle === 'Pure',
    'bg-info': clickStyle === 'Windows',
    'bg-success': clickStyle === 'Shift',
    'text-white': clickStyle !== 'Pure' }">
  {{ clickStyle }} Click
</div>

在 Script 僅 ClickIt 方法,接受來自各不同 Click 方式傳過來的參數,並賦予 Data 中的 clickStyle。

export default {
  name: 'App',
  data() {
    return {
      clickStyle: 'Pure'
    }
  },

  methods: {
    clickIt(styleString){
      this.clickStyle = styleString
    }
  }
}

其他實用使用的 Event Listener 還有包括 mouseover, mouseout。而如果要將 Event 綁定在整個 Window 上而非個別 Element,則可以在 Componenet Mounted 期間在 Window 物件上加入 Event Listener。

mounted() {
  window.addEventListener('keypress', (e) => {
    const inputKey = e.key.toString();
    // console.log(inputKey);
    if (inputKey === '1' || inputKey === '2') {
      this.methods();
    }
    if (inputKey === 'Enter' 
        || inputKey === 'j' 
        || inputKey === 'J') {
      ...
    }
  });
}