1

I'm trying to capture an event on the component root node, but the following does not work. I don't want to just listen on a node in the component. I want to be able to click on any element and then hit backspace to remove it. The code below is a basic example of how I setup my code.

<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>
Soubriquet
  • 3,100
  • 10
  • 37
  • 52

1 Answers1

2

After doing some tests, here is what I discovered:

  1. Having a method called delete won't work. I don't know why, the question remains unanswered here. Rename it to remove, for example.

  2. When trying to catch keyboard events on a div, you may need to add a tabindex attribute for it to work. (See here)

Interactive demo

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>
blex
  • 24,941
  • 5
  • 39
  • 72