简体   繁体   English

在Vue中使用箭头键选择div元素

[英]Selecting div element with arrow keys in Vue

I am trying to navigate through the div elements using arrow keys. 我试图使用箭头键浏览div元素。 I know how to achieve it in JavaScript however I am struggling doing it "vue way". 我知道如何在JavaScript中实现它,但是我正在努力以“正确的方式”实现它。 i know there should not be any differences but it simply does not work. 我知道应该没有任何区别,但这根本行不通。

I have made sandbox for you to check what is going on. 我已经为您准备了沙箱 ,以检查发生了什么。 It is working if I am not using Vue 如果我不使用 Vue,它可以正常工作

In Vue I get the following error because of this line: 在Vue中,由于此行,出现以下错误:

Cannot read property 'focus' of null 无法读取null的属性“ focus”

document.activeElement.parentNode.previousSibling.firstChild.focus();

Can anybody tell me what I am doing wrong? 有人可以告诉我我做错了吗? Is the v-for the error source or are there some other problems? v-for是错误源还是其他一些问题?

It really depends on why you need a focus . 这实际上取决于您为什么需要focus If it's just to highlight something, you can use a secondary variable to track which one you're currently highlighting and add a class to it instead 如果仅是要突出显示某个内容,则可以使用辅助变量来跟踪当前正在突出显示的变量,并向其中添加一个类

https://codesandbox.io/s/300vxzkyk5 https://codesandbox.io/s/300vxzkyk5

<template>
  <div>
    <input ref="input" type="text" @keydown="test" tabindex="0">
    <div ref="test" v-for="item, index in items" :class="{ focus: index === focus }">
       <div>{{ item.title }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { title: "First" },
        { title: "Second" },
        { title: "Third" }
      ],
      focus: null
    };
  },
  methods: {
    test: function(event) {
      switch (event.keyCode) {
        case 38:
          if (this.focus === null) {
            this.focus = 0;
          } else if (this.focus > 0) {
            this.focus--;
          }
          break;
        case 40:
          if (this.focus === null) {
            this.focus = 0;
          } else if (this.focus < this.items.length - 1) {
            this.focus++;
          }
          break;
      }
    }
  }
};
</script>

<style>
div.focus {
  border: 1px solid blue;
}
</style>

Why not take a data-driven approach to this? 为什么不采用数据驱动的方法呢?

You have an array of items. 您有一系列的物品。 You can set an active property on each item and toggle that to true or false . 您可以在每个项目上设置一个活动属性,并将其切换为truefalse

Your up and down keys will change the array pointer and set the current pointer item to true. 您的向上和向下键将更改数组指针并将当前指针项设置为true。 This way you do not have to do any DOM selection. 这样,您不必进行任何DOM选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM