I'm trying to create a custom directive to execute a function when an element is clicked. I can't get it to work, I've looked at the documentation for custom directives and even copying the examples directly from there doesn't see to work.
I'm using single file templates and local directives. Here is the template:
<template>
<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">
<button v-test:click="clicked">Click me</button>
</div>
</div>
</div>
</template>
And here is the script:
<script>
export default {
name: 'App',
components: {
},
directives: {
test: {
bind(el, binding) {
const type = binding.arg;
const fn = binding.value;
el.addEventListener(type, fn)
}
}
},
methods: {
clicked() {
alert('text');
}
}
}
</script>
I have tried using Vue 3 syntax (beforeMount rather than bind), as well as global directives but these things don't seem to work either. Does anyone know what I'm doing wrong?
The alert box will appear as soon as the page is loaded if I provide parentheses to the value passed into v-test
. Either way nothing happens when the button is clicked.
Vue3 has changed the syntax for directives. New Syntax
bind → beforeMount
inserted → mounted
beforeUpdate (new)
update (has been removed)
componentUpdated → updated
beforeUnmount (new)
unbind → unmounted