Reputation: 3415
I've got a simple directive:
HTML:
<div id="app">
<div v-sample:callback="greet"></div>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
files: [],
},
methods: {
greet: function (arg) {
alert(arg);
},
},
});
</script>
JS:
Vue.directive('sample', {
bind: function (el, binding, vnode) {
el.addEventListener('...', function () {
// ...
callback.call(arg, ...);
});
},
});
However, I'm unclear of the appropriate syntax to get the function and evaluate. What's the proper way to do this from within a directive?
Upvotes: 8
Views: 5292
Reputation: 111
Working on Nuxt3 + Vue3
// Run this module from some defineNuxtPlugin config (client only)
export default (vueInstance) => {
// Click outside some element
vueInstance.directive('click-outside', {
created(el, binding, vnode, prevVnode) {
el.clickOutsideEvent = function (event) {
console.log(binding.instance.close)
if (!(el == event.target || el.contains(event.target))) {
if(binding.instance[binding.value]) {
binding.instance[binding.value](event)
}
}
}
document.body.addEventListener('click', el.clickOutsideEvent)
},
beforeUnmount(el, binding, vnode, prevVnode) {
document.body.removeEventListener('click', el.clickOutsideEvent)
}
})
}
<div v-click-outside="'close'">
</div>
Upvotes: 0
Reputation: 1
Maybe you can do like this.
<div v-mydirect:fn="params"></div>
Vue.directive('mydirect', {
bind (el, binding,vnode) {
let that = vnode.context
that[binding.arg](binding.value)
}
})
Upvotes: -1
Reputation: 193261
You can use binding.value
which should be a function in this case. It's already prebound to correct context so just call it (pass anything in it if you need something):
Vue.directive('sample', {
bind: function (el, binding, vnode) {
el.addEventListener('click', function () {
binding.value()
});
},
});
Upvotes: 7