【问题标题】:Vue 2 event listener on component root组件根目录上的 Vue 2 事件监听器
【发布时间】:2018-12-27 20:22:20
【问题描述】:

我正在尝试捕获组件根节点上的事件,但以下操作不起作用。我不想只听组件中的一个节点。我希望能够单击任何元素,然后按退格键将其删除。下面的代码是我如何设置代码的基本示例。

<template>
   <div v-on:keydown.delete="delete()">
      <img id="image" src="..." v-on:click="set_active()">
   </div>
</template>
<script>
export default {
   return {
      data() {
          active: ''
      },
      methods: {
          delete(){
              delete this.$refs[this.active][0];
          },
          set_active() {
             this.active = event.target.getAttribute('id');
          }
      }
   }
}
</script>

【问题讨论】:

  • 尝试添加&lt;img ref="myImage" ...&gt; 然后this.$refs.myImage.hide()
  • @ulou 不起作用:/

标签: javascript events vuejs2


【解决方案1】:

在做了一些测试后,我发现:

  1. 拥有一个名为delete 的方法将不起作用。我不知道为什么,这个问题仍然没有答案here。例如,将其重命名为 remove

  2. 当试图捕捉 div 上的键盘事件时,您可能需要添加 tabindex 属性才能使其工作。 (See here)

互动演示

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      images: [
        "https://media.giphy.com/media/3ohs7KtxtOEsDwO3GU/giphy.gif",
        "https://media.giphy.com/media/3ohhwoWSCtJzznXbuo/giphy.gif",
        "https://media.giphy.com/media/8L0xFP1XEEgwfzByQk/giphy.gif"
      ],
      active: null
    };
  },
  methods: {
    set_active(i) {
      this.active = i;
    },
    remove() {
      if (this.active !== null) {
        this.images = this.images.filter((_, i) => i !== this.active);
        this.active = null;
      }
    }
  }
});

var vm = new Vue({
  el: '#app'
});
div {
  outline: none; /* Avoid the outline caused by tabindex */
  border: 1px solid #eee;
}

img {
  height: 80px;
  border: 4px solid #eee;
  margin: .5em;
}

img:hover {
  border: 4px solid #ffcda9;
}

img.active {
  border: 4px solid #ff7c1f;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>
<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <div @keydown.delete="remove" tabindex="0">
    <img
      v-for="(img, i) in images"
      :key="i"
      :src="img"
      :class="{ active: active === i }"
      @click="set_active(i)"
    />
  </div>
</template>

【讨论】:

  • 哇太棒了!作品。谢谢。为什么我需要tabindex=0
  • 你会发现一些信息here,尤其是描述部分
猜你喜欢
  • 2021-12-27
  • 2020-06-25
  • 2019-07-20
  • 1970-01-01
  • 2018-05-15
  • 2019-10-15
  • 1970-01-01
  • 2019-08-09
  • 2014-07-27
相关资源
最近更新 更多