Search code examples
vue.jsvue-component

How to pass dynamic argument in vuejs custom directive


<template>
    <div>
        <img v-directive:dynamic_literal />
    </div>
</template>

E.g. dynamic_literal = 'ok' such that in custom directive:

Vue.directive('directive', {
    bind(el, binding) {  binding.arg  // should return 'ok'

How can I use dynamic_literal as a variable or a constant whose value should be assigned under data or prop.

I tried with v-directive:{{dynamic_literal}} and :v-directive="dynamic_literal" but no use.

Thanks in advance!


Solution

  • 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