使用jquery-chosen插件更新vuejs模型值 [英] Update vuejs model value using jquery-chosen plugin

查看:181
本文介绍了使用jquery-chosen插件更新vuejs模型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图将 jquery-chosen 与vue一起使用,问题在于此插件隐藏了实际选择的内容我应用了v-model,因此当我选择一个值时,vue不会将其识别为选择更改事件,并且模型值不会更新.

Trying to use jquery-chosen with vue, the problem is that this plugin hides the actual select that I applied v-model, so when I select a value vue doesn't recognize it as a select change event and model value is not updated.

当我选择某些东西时,select的值实际上正在更改,我已经用console.log进行了检查,以查看选择的值.

The value of the select is being changed actually when I select something, I've inspected this with console.log to see the selected value.

http://jsfiddle.net/qfy6s9Lj/3/

我可以做到vm.$data.city = $('.cs-select').val() 似乎可以正常工作, 但是还有其他选择吗?如果更改了select的值,为什么vue看不到呢?

I could do vm.$data.city = $('.cs-select').val(), that seems to work, But is there another option? If the value of the select was changed why vue doesn't see this?

推荐答案

答案: http://jsfiddle.net/qfy6s9Lj/5/

<div id='search-results'>
    Vue model value <br>
    {{city}}
    <hr>
    Select value:
    <select class="cs-select" v-chosen>
       <option value="Toronto">Toronto</option>
       <option value="Orleans">Orleans</option>
    </select>
</div>

Vue.directive('chosen', {
    bind: function () {
        var vm = this.vm;
        this.el.options = vm.cities;
        this.el.value = vm.city;       

        $(this.el).chosen({
            inherit_select_classes: true,
            width: '30%',
            disable_search_threshold: 999})
        .change( function() {
             vm.city = this.el.value;
         }.bind(this)
      );
    }
});

var vm = new Vue({
  data: {
      city: 'Toronto',
      cities: ['Toronto', 'Orleans']
  }
}).$mount("#search-results");

更新:一个更好的解决方案(感谢simplesmiler): http://jsfiddle.net/simplesmiler/qfy6s9Lj/8/

UPDATE: an even better solution (thanks to simplesmiler): http://jsfiddle.net/simplesmiler/qfy6s9Lj/8/

这篇关于使用jquery-chosen插件更新vuejs模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆