本文介绍了如何在 Vue.js 上的自定义指令上捕获单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Vue.js 并遇到了一个练习示例,我需要实现一个自定义指令,该指令可以在v-on"上工作.这意味着我需要在我的自定义指令上捕获点击事件并调用一个方法.

I am trying to learn Vue.js and came to an practice example where I need to implement a custom directive whice works lice 'v-on'.This means that i need to capture the click event on my custom directive and call a method.

我想到的模板.

<template>
    <h1 v-my-on:click="alertMe">Click</h1>
</template>

问题是我不知道如何在自定义指令中捕获点击事件.请原谅下面笨拙的代码.

The problem is i don't know how to capture the click event in the custom directive. Excuse the clumsy code below.

<script>
    export default {
        methods: {
            alertMe() {
                alert('The Alert!');
            }
        },
        directives: {
            'my-on': {
                bind(el, binding, vnode) {
                    console.log('bind');

                    el.addEventListener('click',()=>{
                        console.log('bind');
                        vnode.context.$emit('click');
                    });
                },

            }
        }
    }
</script>

谁能帮我理解这是如何工作的?我没有找到任何类似的例子.

Can anyone help me understand how this works? I didn't manage to find any example of something similar.

推荐答案

经过更多搜索,我找到了这个解决方案:

After some more searching i came to this solution:


<template>
  <h1 v-my-on:click="alertMe">Click me!</h1>
</template>

<script>

  export default {

    methods: {

      alertMe() {

        alert('The Alert!');

      }

    },

    directives: {

      'my-on': {

        // Add Event Listener on mounted.
        bind(el, binding) {
          el.addEventListener(binding.arg, binding.value);
        },

        // Remove Event Listener on destroy.
        unbind(el, binding) {
          el.removeEventListener(binding.arg, binding.value);
        }

      }

    }

  }
</script>

这篇关于如何在 Vue.js 上的自定义指令上捕获单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 05:16