14

我目前使用 Vue.JS 2.0,我想从自定义指令中更新一个 Vue 实例的模型,但我正在寻找一种很好的方法,这是因为我试图创建一个自定义指令来实现 JQueryUI-Datepicker 代码如下:

<input type="text" v-datepicker="app.date" readonly="readonly"/>

Vue.directive('datepicker', {
  bind: function (el, binding) {
    $(el).datepicker({
      onSelect: function (date) {
        //this is executed every time i choose an date from datepicker
        //pop.app.date = date; //this work find but is not dynamic to parent and is very dirty
        Vue.set(pop, binding.expression, date); //this should work but nop
      }
    });
  },
  update: function (el, binding) {
    $(el).datepicker('setDate', binding.value);
  }
});

var pop = new Vue({
    el: '#popApp',
    data: {
        app: {
            date: ''
        }
    }
});

有人知道如何从指令中以动态方式更新 pop.app.date,我知道 binding.expression 在此示例中返回 app.date 并且 date 返回在 datepicker 中选择的当前日期,但我不知道如何更新模型从指令

4

2 回答 2

5

这可以解决问题:

// vnode (third argument is required).
bind: function (el, binding, vnode) {
    $(el).datepicker({
        onSelect: function (date) {
            // Set value on the binding expression.
            // Here we set the date (see last argument).
            (function set(obj, str, val) {
                str = str.split('.');
                while (str.length > 1) {
                    obj = obj[str.shift()];
                }
                return obj[str.shift()] = val;
             })(vnode.context, binding.expression, date);
         }
    });
},

参考:https ://stackoverflow.com/a/10934946/2938326

于 2017-01-30T13:41:11.650 回答
0

只是为了跟进@Kamal Khan 的回答(效果很好)。

我刚刚完成了以下操作并开始工作(下)。这消除了查找对象并依赖 Vue 的设置功能来设置值。

bind: function (el, binding, vnode) {
    $(el).datepicker({
        onSelect: function (date) {
             Vue.set(vnode.context, binding.expression, date);
         }
    });
},

我的完整指令是:

  Vue.directive("datepicker",{
    bind(el,binding, vnode) {
       console.log(binding);
       var self = el
      $(self).datepicker({
        dateFormat:'mm-dd-yy',
        onSelect: function (date) {
            Vue.set(vnode.context, binding.expression, date);
        }
    });      
    },
    updated: function (el,binding) {
    }
 });  

然后我可以在模板或 html 中调用它:

 <input v-model="dtime" v-datepicker="dtime"> 

dtime 是我的数据模型值。

希望这对其他人有所帮助,因为这让我发疯了。

于 2018-09-26T20:16:38.907 回答