组件根目录上的 Vue 2 事件侦听器



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

<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>

在做了一些测试之后,这是我发现的:

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

  2. 尝试捕获div 上的键盘事件时,可能需要添加 tabindex 属性才能使其正常工作。(看这里)

交互式演示

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>

最新更新