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?
A custom directive is defined as an object containing lifecycle hooks similar to those of a component. The hooks receive the element the directive is bound to. Here is an example of a directive that focuses an input when the element is inserted into the DOM by Vue:
You can actually get dynamic arguments in Vue directives by using the vnode parameter passed to the directive hook functions. We'll use the argument itself as the property name that we want to access in the context of vnode.
Custom directives, on the other hand, are mainly intended for reusing logic that involves low-level DOM access on plain elements. A custom directive is defined as an object containing lifecycle hooks similar to those of a component. The hooks receive the element the directive is bound to.
The Custom Directives allows the developers to create and use some custom functions easily on the elements. Like the in-built directives that are like v-model, v-for, v-if, etc., we can create our own directives which will according to what we set it. It allows reusing some logic by having access to the lower level of DOM.
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()
});
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With