update model from custom directive VueJS

后端 未结 2 860
我寻月下人不归
我寻月下人不归 2021-02-19 07:33

I currently use Vue.JS 2.0 and I want to update the model off one Vue instance from an custom directive, but im looking a nice way to do it, this is because i trying to create a

相关标签:
2条回答
  • 2021-02-19 07:43

    This will do the trick:

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

    Reference: https://stackoverflow.com/a/10934946/2938326

    0 讨论(0)
  • 2021-02-19 07:43

    Just to follow up on @Kamal Khan's answer (which works great).

    I have just done the following and got it to work (below). This removes finding the object and relies on Vue's set functionality to set the value.

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

    My full directive is:

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

    I can then call this in the template or html with:

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

    with dtime being my data model value.

    Hope this helps somebody else as this drove me nuts.

    0 讨论(0)
提交回复
热议问题