Vue Cli 3 使用 simple-keyboard 實作螢幕虛擬鍵盤功能
                    Vue Cli 3 使用 simple-keyboard 實作能在 Web 網頁呈現的螢幕虛擬鍵盤功能,並將 simple-keyboard 建立在子組件,以便同時建立多個虛擬鍵盤實例。
安裝 simple-keyboard
先切換至 Vue Cli 專案目錄:
cd test
npm 安裝虛擬鍵盤插件 simple-keyboard:
npm install vue-i18n
simple-keyboard 設定
將虛擬鍵盤插件 simple-keyboard 建立成子組件的方式,以便建立多個虛擬鍵盤實例,檔案結構如下:
src/ ... ├── components # Vue 公共組件 │ └── SimpleKeyboard.vue # 自訂新增的子組件 ├── App.vue # 項目入口 ...
新增子組件 src/components/SimpleKeyboard.vue:
<template>
  <div :class="keyboardClass"></div>
</template>
<script>
import Keyboard from "simple-keyboard";       // 引入 simple-keyboard
import "simple-keyboard/build/css/index.css"; // 引入 simple-keyboard 預設提供的 CSS
export default {
  name: "SimpleKeyboard",
  props: {
    keyboardClass: {
      default: "simple-keyboard",
      type: String
    },
    input: {
      type: String
    }
  },
  data: () => ({
    keyboard: null
  }),
  mounted() {
    // 要使用多個虛擬鍵盤實例必須定義不同的 className [參考 How to add multiple keyboard instances - simple-keyboard - Francisco Hodge] (https://hodgef.com/simple-keyboard/questions-answers/add-multiple-keyboard-instances/)
    this.keyboard = new Keyboard('.' + this.keyboardClass, {
      onChange: this.onChange,
      onKeyPress: this.onKeyPress,
      // 自訂鍵盤
      layout: {
        default: ["1 2 3", "4 5 6", "7 8 9", "0 {bksp}"]
      },
      // 自訂按鍵名稱
      display: {
          '{bksp}': '← 刪除'
      }
    });
  },
  methods: {
    onChange(input) {
      this.$emit("onChange", input);
    },
    onKeyPress(button) {
      this.$emit("onKeyPress", button);
    },
  },
  watch: {
    input(input) {
      this.keyboard.setInput(input);
    }
  }
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
網頁 UI
設定不同名稱的 :keyboardClass,即可建立多個虛擬鍵盤實例 (這裡建立兩個),編輯 src/App.vue:
<template>
  <div>
    <div style="float: left; margin-right: 2%; width: 49%;">
      <label>
        input A
        <input type="text" v-model="inputA">
      </label>
      <SimpleKeyboard @onChange="changeA" :keyboardClass="'simple-keyboard-a'" :input="inputA" />
    </div>
    <div style="float: left; width: 49%;">
      <label>
        input B
        <input type="text" v-model="inputB">
      </label>
      <SimpleKeyboard @onChange="changeB" :keyboardClass="'simple-keyboard-b'" :input="inputB" />
    </div>
  </div>
</template>
<script>
import SimpleKeyboard from "./components/SimpleKeyboard"; // 引入子組件
export default {
  components: {
    SimpleKeyboard
  },  
  data () {
    return {
      inputA: null,
      inputB: null
    }
  },
  methods: {
    changeA (input) {
      this.inputA = input;
    },
    changeB (input) {
      this.inputB = input;
    }
  }
}
</script>
執行程式並測試結果
執行程式:
npm run serve
瀏覽器測試結果:

參考
                            本著作係採用創用 CC 姓名標示-相同方式分享 3.0 台灣 授權條款授權.