从自定义指令VueJS更新模型

Dav*_*ola 14 javascript jquery-ui vuejs2

我目前使用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: ''
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

有人知道如何从指令动态更新pop.app.date,我知道binding.expression在这个例子中返回app.date和date返回在datepicker中选择的当前日期,但我不知道如何更新模型从指令

Kam*_*han 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);
         }
    });
},
Run Code Online (Sandbox Code Playgroud)

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