0
v模型指令僅限於input
事件。但我希望它支持jquery change
事件,以便我可以使用jquery插件(如bootstrap-toggle),而無需編寫單獨的代碼來操作這些字段。Vuejs:如何編寫類似於v模型的指令,用於jquery插件
我面臨的主要挑戰是如何在jquery change
事件中更新綁定到元素的值。我試着在change
事件觸發input
事件被解僱,但它沒有奏效。
這裏是我想要實現:
HTML:
<input id="dayparting_switch" v-observe="options.dayparting" v-model="options.dayparting" :cheked="options.dayparting" data-off="Disabled" data-on="Enabled" data-toggle="toggle" type="checkbox">
自定義指令:
Vue.directive('observe', {
bind: function(el, bind, vnode) {
$(el).is(':checkbox') ? $(el).prop('checked', !!bind.value) : $(el).val(bind.value);
$(el).change(function() {
var newVal = $(el).is(':checkbox') ? $(el).prop('checked') : $(el).val();
// Here comes problem: how to set new value to options.dayparting ?
// 1) bind.value = newVal won't trigger any update
// 2) this.dispatchEvent(new Event('input')) also doesn't work
// 3) Only quirky way of doing this is to parse bind.expression to get object and keys and then use Vue.set
var lastDot = bind.expression.lastIndexOf('.');
var object = bind.expression.substring(0, lastDot);
var key = bind.expression.substr(lastDot+1);
Vue.set(eval('vnode.context.' + object), key, newVal);
});
}
});
上述方法實際上是爲我工作,但我認爲這是不是一個完美的方法。例如,它不會工作v-observe="options[option_name]"
是否有任何簡單或標準的方法來實現這一目標?
請勿將jQuery與VueJS混合使用。這真的不是個好主意。你可以用VueJS做所有事情 –