VueJS Custom Direct function as argument

I have 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 do not know what syntax is needed to get the function and evaluate. What is the correct way to do this from a directive?

+4
source share
1 answer

You can use binding.valuewhich should be a function in this case. It already precedes the correct context, so just name it (pass something in it if you need something):

Vue.directive('sample', {
  bind: function (el, binding, vnode) {
    el.addEventListener('click', function () {
      binding.value()
    });
  },
});
+3
source

Source: https://habr.com/ru/post/1674360/


All Articles