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做所有事情 –