javascript - 组件根上的 Vue 2 事件监听器

标签 javascript events vuejs2

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

<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 的方法将不起作用。我不知道为什么,这个问题仍然没有答案here 。例如,将其重命名为 remove

  2. 当 try catch 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>

关于javascript - 组件根上的 Vue 2 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950463/

相关文章:

vue.js - 运行VueJS项目时出现NET::ERR_CERT_INVALID错误

javascript - 在 C# 中重现 JS PBKDF2 哈希

javascript - 在嵌套对象上实现代理

wpf - 直接路由事件问题

javascript - 第一个 li 项的 Jquery 点击事件

javascript - Bootstrap-vue - 如何以编程方式显示/隐藏 b-table 列

javascript - 如何在 tinyMCE 中添加字体大小的工具栏?

javascript - 无法附加或发布 CKEditor 值

php - 在日历中显示事件 php mysql

vue.js - 在导航选项卡上切换处于事件状态的 css 类