Monday, April 9, 2018

[Vue.js][Example] Custom directive with click event

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <h1>Directives</h1>
                <p><button v-myon:click="alertMe">Click me</button></p>
                <p>Clicked amount: {{count}}.</p>
            </div>
        </div>
    </div>
</div>

<script>
    new Vue({
        el:"#app",
        directives:{
            "myon":{
                bind(el,binding){
                    el.addEventListener(binding.arg, binding.value);
                }
            },
        },
        data(){
            return {count:0};
        },
        methods:{
            alertMe(){
                this.count++;
                alert("You clicked the button !");
            }
        }
    });
</script>

Reference

https://stackoverflow.com/questions/48486116/how-can-i-capture-click-event-on-custom-directive-on-vue-js

No comments :

Post a Comment