How to pass dynamic argument in vuejs custom directive

I don't think there is any way you could make the argument dynamic, but the value can be.

console.clear()

Vue.directive("test", {
  bind(el, binding){
    console.log(binding)
  },
  update(el, binding){
    console.log(binding)
  }
})

new Vue({
  el:"#app",
  data:{
    dynamic_literal: 'ok'
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <h1 v-test="dynamic_literal">Hello World</h1>
  <button @click="dynamic_literal='not ok!'">Change literal</button>
</div>

Note when you run the above snippet that the value property changes in the log when you click the button.


A little late but maybe it's of some use... 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. This also works with computed properties, for example.

Vue.directive('directive', function(el, binding, vnode){
    el.innerHTML = vnode.context[binding.arg];
});

new Vue({
    el: '#app',
    template: '<div v-directive:argument></div>',
    data: {
        argument: 0
    },
    mounted() {
        setInterval(() => ++this.argument, 1000);
    }
});

(using the function shorthand for directives here)

JSFiddle


working for me:

<div v-mydirective:[dynamicArg]="foo">

to access it with binding.arg

more info: https://github.com/vuejs/rfcs/blob/master/active-rfcs/0003-dynamic-directive-arguments.md