【问题标题】:Using a custom directive with $index of v-for使用带有 v-for 的 $index 的自定义指令
【发布时间】:2016-03-14 13:41:46
【问题描述】:

我在 v-for 中有一个自定义指令。我需要将 $index 的值传递给自定义指令,以便能够将 datepicker 值保存在一个数组中(每个产品都有一个日期)。不过,$index 在数组中总是有一个 undefined 值。

   <tr v-for="result in results">
      <td>
           <input v-model="shoppingCart[$index].productStartDate" type="text" v-datepicker='shoppingCart[$index].productStartDate'>
      </td>

问题在于字符串 $index 是进入自定义指令的内容。

客户指令:

 Vue.directive('datepicker', {

        bind: function () {
            var vm = this.vm;
            var key = this.expression;
            $(this.el).datepicker({
                onSelect: function (date) {
                    vm.$set(key, date);
                }
            });
        },
        update: function (val) {
            $(this.el).datepicker('setDate', val);
        }

    });

我曾尝试使用 this.arg 传递对 $index 的引用,但找不到传递闭包以获取值的方法,但均未奏效,我一定是做错了什么?

【问题讨论】:

  • 只是一个问题,您为什么在指令中使用引号和箭头?我虽然像属性一样使用指令,但我第一次看到这种表示法
  • @YerkoPalma - 感谢您指出这一点,这是我将 Laravel 刀片语法转换为 html 时的错误。现在已经修复了
  • 面临同样的问题....帮助任何人?

标签: javascript vue.js


【解决方案1】:

对于 Vue.js 2.x,他们建议使用数据集来传递值 所以你可以在 HTML 元素中添加 :data-index="index" 并像这样在指令中获取它:

Vue.directive('yourDirective', {
  bind: function (el, binding, vnode) {
    console.log('index of element', el.dataset.index); 
  }
}
<div 
  v-yourDirective
  v-for="(test,index) in tests" 
  :data-index="index"
>
  
</div>

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2019-05-22
    • 1970-01-01
    • 2014-08-28
    • 2015-03-06
    相关资源
    最近更新 更多