Reputation: 1834
I'm working with custom directives and want to create one such that you could use separate events for firing it based on what you pass it in the markup.
v-example-directive.mousedown="exampleFunction"
v-example-directive.mouseup="exampleFunction"
v-example-directive.click="exampleFunction"
I've looked through Vues Documentation and tried searching how to do this but have found nothing about this. Is this something that could be done such that you can create one directive and have either multiple functions inside or the ability to define what type of event you want? Or would I have to register multiple directives to achieve this?
Upvotes: 5
Views: 3634
Reputation: 4406
You can achieve this by using args
or modifiers
in your custom vue directive.
To use these hooks, you have to look at the binding
parameter of the directive. This parameter includes a whole set of properties that you can use to bake your custom directive.
In your case, you would want to look for either the binding.modifier
or binding.arg
depending on the HTML structure you desire:
Argument markup:
<img v-example-directive:mouseup>
Modifier markup:
<img v-example-directive.mouseup>
Now that you have added a "flag", you can check for it in the directive:
Vue.directive('example-directive', {
bind(el, binding) {
if (binding.arg == 'mouseup') {} // Using argument markup
if (binding.modifiers.mouseup) {} // Using modifier markup
}
})
Example:
Vue.directive('example-directive', {
bind(el, binding) {
if (binding.arg == 'mousedown') { // Check by argument given to directive
el.addEventListener("mousedown", () => {
binding.value() // The function provided by the directive
});
}else if (binding.modifiers.mouseup) { //check by modifier
el.addEventListener("mouseup", () => {
binding.value()
});
}
}
})
let x = new Vue({
el:"#app",
methods: {
clicked() {
console.log("clicked")
}
}
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<button v-example-directive:mousedown="clicked">mousedown</button>
<button v-example-directive.mouseup="clicked">mouseup</button>
<!-- ... -->
</div>
Upvotes: 3