Vuejs:如何编写类似于v-model的指令,用于jquery插件

时间:2017-03-14 07:18:06

标签: vue.js vuejs2

v-model指令仅限于input事件。但我希望它也支持jquery change事件,这样我就可以使用像bootstrap-toggle这样的jquery插件而无需编写单独的代码来操作这些字段。

我面临的主要挑战是如何在jquery change事件上更新绑定到元素的值。我尝试在input事件被触发change事件被触发,但它没有用。

这是我想要实现的目标:

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]"

有没有简单或标准的方法来实现这个目标?

1 个答案:

答案 0 :(得分:1)

在Vue 1中,可以编写双向绑定指令(如v-model),但在Vue 2中,可以使用组件进行编写。

查看Wrapper Component Example