2016-10-12 121 views
13

我目前使用Vue.JS 2.0,我想從一個自定義指令更新一個Vue實例的模型,但即時通訊尋找一個很好的方式來做到這一點,這是因爲我試圖創建一個實現jQueryUI的,日期選擇器的代碼定製指令是如下:更新模型自定義指令VueJS

<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回報。日期和日期返回datepicker中選擇的當前日期,但我不知道如何從指令更新模型

+1

你設法找到一個解決方案@bal? –

+0

@chrisEdwards是 –

+0

請問您能詳細說明一下嗎? –

回答

4

這將做到這一點:

// 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

+0

這個工作,你能解釋我這個代碼做什麼? –

+1

自我調用函數通過分割點並循環遍歷點符號(例如app.date),直到我們到達所需的鍵(在您的示例中爲** date **),然後根據您的值設置其值提供作爲最後一個參數。 –

相關問題