How can I simulate a different button pressed when

2019-02-27 23:15发布

Is it possible using vue.js to simulate another button pressed when a button is pressed?

For example, if I press the (Arrow down) button, I would like it to be represented as if I had pressed the TAB button.

Explanation why am I trying to implement this:

After clicking on a DropDown list, the list with all the elements opens up. In this list I have an <input> element as a search box, which is used to search other elements in the list (all the other elements are directly listed under that search box). Currently as the DropDown list opens the focus is set automatically to the search box. To go down to the next item, you have to press the TAB button. But I need to achieve this with the (Arrow down) button.

2条回答
乱世女痞
2楼-- · 2019-02-27 23:33

I think you're asking how to simulate a TAB keypress when the user presses DOWN with the goal of moving the focus to the next focusable input.

Instead of rewriting the key-event, you could call HTMLElement#focus() on the next sibling:

<!-- TEMPLATE -->
<input type="text"
    @keydown.up.stop.prevent="prevInput"
    @keydown.down.stop.prevent="nextInput"
    v-for="i in 5">

// SCRIPT
methods: {
  nextInput(e) {
    const next = e.currentTarget.nextElementSibling;
    if (next) {
      next.focus();
    }
  },
  prevInput(e) {
    const prev = e.currentTarget.previousElementSibling;
    if (prev) {
      prev.focus();
    }
  },
}

<script src="https://unpkg.com/vue@2.5.17"></script>

<div id="app">
  <input type="text"
         @keydown.up.stop.prevent="prevInput"
         @keydown.down.stop.prevent="nextInput"
         v-for="i in 5">
</div>

<script>
new Vue({
  el: '#app',
  methods: {
    nextInput(e) {
      const next = e.currentTarget.nextElementSibling;
      if (next) {
        next.focus();
      }
    },
    prevInput(e) {
      const prev = e.currentTarget.previousElementSibling;
      if (prev) {
        prev.focus();
      }
    },
  }
})
</script>

查看更多
老娘就宠你
3楼-- · 2019-02-27 23:59

Sure, add a ref to tab

<div class="tab" ref="tab">

Then capture arrow click:

arrowClick() {
   this.$refs.tab.click()
}
查看更多
登录 后发表回答