如何在vue.js自定义指令中传递动态参数

Suk*_*der 5 vue.js vue-component

<template>
    <div>
        <img v-directive:dynamic_literal />
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

例如dynamic_literal ='ok'这样在自定义指令中:

Vue.directive('directive', {
    bind(el, binding) {  binding.arg  // should return 'ok'
Run Code Online (Sandbox Code Playgroud)

如何将dynamic_literal用作变量或常量,其值应在data或prop下分配。

我尝试使用v-directive:{{dynamic_literal}}和:v-directive =“ dynamic_literal”,但没有用。

提前致谢!

Chr*_*llo 6

为我工作:

<div v-mydirective:[dynamicArg]="foo">
Run Code Online (Sandbox Code Playgroud)

访问它binding.arg

更多信息:https://github.com/vuejs/rfcs/blob/master/active-rfcs/0003-dynamic-directive-arguments.md


Ale*_*ios 5

有点晚了,但也许它有一些用处...您实际上可以通过使用vnode传递给指令挂钩函数的参数在 Vue 指令中获取动态参数。我们将使用参数本身作为我们想要在 的上下文中访问的属性名称vnode。例如,这也适用于计算属性。

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

(在此处使用指令的函数简写

JSFiddle