如何在vuejs自定义指令中传递动态参数

问题描述 投票:0回答:6
<template>
    <div>
        <img v-directive:dynamic_literal />
    </div>
</template>

例如动态文字 = '好的' 这样在自定义指令中:

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

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

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

提前致谢!

vue.js vue-component
6个回答
6
投票

为我工作:

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

使用

binding.arg

访问它

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


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);
    }
});

(此处使用 函数简写 作为指令)

JSFiddle


2
投票

我认为没有任何方法可以使论证变得动态,但价值可以。

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>

请注意,当您运行上述代码片段时,单击按钮时日志中的

value
属性会发生变化。


1
投票

无法将动态参数传递给指令,但您可以创建一个中间组件来动态渲染通过 prop 传递的值。

export default {
  render(createElement) {
    return createElement(
      'img', {
        directives: [
          {
            name: 'directive',
            arg: this.literal,
          },
        ],
      }
    );
  },
  props: {
    literal: {
      type: String,
      required: true,
    },
  },
};

所以这段代码应该可以解决问题

<template>
    <div>
        <new-img-component :literal="dynamic_literal" />
    </div>
</template>

1
投票

我建议你可以尝试做这样的事情:

<div v-mydirective="{text: dynamic_literal}">

with

dynamic_literal
是组件的 props/data 中的变量


0
投票

我遇到了类似的问题,其中我的 binding.value 本来是动态的,但它不会更新或做出反应。 我的解决方案是在创建指令时添加

beforeUpdate
。最初,我只使用
mounted
,因此提供的第一个值始终保留。

© www.soinside.com 2019 - 2024. All rights reserved.