Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Custom Directive Function as Argument

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?

like image 283
Stussa Avatar asked Apr 08 '17 07:04

Stussa


People also ask

What is a custom directive in Vue?

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:

How to get dynamic arguments in Vue directives?

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.

What is the difference between a custom Directive and component?

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.

What are custom directives in angular?

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.


1 Answers

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()
    });
  },
});
like image 138
dfsq Avatar answered Oct 12 '22 01:10

dfsq