vue中使用键盘快捷键选中输入框

120 阅读1分钟

vue中使用键盘快捷键选中输入框

在这里插入图片描述 main.js中进行全局挂载

import keyboardjs from "keyboardjs";
Vue.prototype.$keyboard = keyboardjs;
<template>
  <div class="box-card">
    <h2>Keyboard</h2>
    <h4>ctrl+s 选中 code 输入框</h4>
    <h4>ctrl+c 选中 description 输入框</h4>
    <h4>ctrl+d 选中 type 输入框</h4>
    <h4>ctrl+f 选中 branch 输入框</h4>
    <SearchForm
      ref="searchForm"
      :form-data="formData"
      :submit-event="submitEvent"
      :form-items="searchItem.formItems"
      :reset-event="resetEvent"
      :show-all-fold="false"
      :show-filter-select="false"
    >
    </SearchForm>
  </div>
</template>

<script>
import SearchForm from "@/components/SearchForm/index.vue";
import { searchItem } from "./config.js";
export default {
  name: "Keyboard",
  components: {
    SearchForm,
  },
  data() {
    return {
      input: "",
      // 搜索表单数据
      formData: {
        code: "",
        description: "",
        type: "",
        branch: "",
      },
      // 搜索项
      searchItem: searchItem,
    };
  },

  mounted() {
    this.$keyboard.bind(["ctrl+s", "command+s"], (e) => {
      e.preventDefault();
      this.focusInput("code");
    });
    this.$keyboard.bind(["ctrl+c", "command+c"], (e) => {
      e.preventDefault();
      this.focusInput("description");
    });
    this.$keyboard.bind(["ctrl+d", "command+d"], (e) => {
      e.preventDefault();
      this.focusInput("type");
    });
    this.$keyboard.bind(["ctrl+f", "command+f"], (e) => {
      e.preventDefault();
      this.focusInput("branch");
    });
  },
  beforeDestroy() {
    // 解绑快捷键
    this.$keyboard.unbind("ctrl+s");
    this.$keyboard.unbind("ctrl+c");
    this.$keyboard.unbind("ctrl+d");
    this.$keyboard.unbind("ctrl+f");
  },
  methods: {
    submitEvent() {},
    resetEvent() {},
    // 聚焦输入框
    focusInput(refName) {
      const input = this.$refs.searchForm.$refs[refName][0];
      if (input && input.$el) {
        input.$el.querySelector("input").focus();
      }
    },
  },
};
</script>