Update vuejs model value using jquery-chosen plugin

╄→гoц情女王★ 提交于 2019-12-03 13:06:34

Answer: 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");

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

@swift's answer got pretty close, but as @bertrand pointed out, it doesn't work for multiselects. I've worked something out that works with both cases: http://jsfiddle.net/seanwash/sz8s99xx/

I would have just commented but I don't have enough rep to do so.

Vue.directive('chosen', {
    twoWay: true, // note the two-way binding
    bind: function () {
        $(this.el)
            .chosen({
                inherit_select_classes: true,
                width: '30%',
                disable_search_threshold: 999
            })
            .change(function(ev) {
                // two-way set
                // Construct array of selected options
                var i, len, option, ref;
                var values = [];
                ref = this.el.selectedOptions;
                for (i = 0, len = ref.length; i < len; i++) {
                    option = ref[i];
                    values.push(option.value)
                }
                
                this.set(values);
                
            }.bind(this));
    },
    update: function(nv, ov) {
        // note that we have to notify chosen about update
        $(this.el).trigger("chosen:updated");
    }
});

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

I am opened for other suggestions, but for the time-being I did it this way:

html

<div id='search-results'>
    {{city}}
    <select class="cs-select" v-model='city'>
        <option value="Toronto">Toronto</option>
        <option value="Orleans">Orleans</option>
    </select>
</div>

js

window.vm = new Vue({
  el: '#search-results',
  data: {
    city: 'Toronto',
  }
})

$('.cs-select').chosen({
    inherit_select_classes: true,
    width: '30%'
}).change( function() {
    vm.$data.city = $('.cs-select').val()
})

Update: Be advised this doesn't work from within a v-for loop. A related question that deals with that is available here.

Going off of @kaktuspalme's solution, and with help from my friend Joe Fleming, I came up with a solution that works with Vue 2 and allows single and multiple selections:

Vue.directive('chosen', {
    inserted: function(el, binding, vnode) {
        jQuery(el).chosen().change(function(event, change) {
            if (Array.isArray(binding.value)) {
                var selected = binding.value;
                if (change.hasOwnProperty('selected')) {
                    selected.push(change.selected);
                } else {
                    selected.splice(selected.indexOf(change.deselected), 1);
                }
            } else {
                var keys = binding.expression.split('.');
                var pointer = vnode.context;
                while (keys.length > 1)
                    pointer = pointer[keys.shift()];
                pointer[keys[0]] = change.selected;
            }
        });
    },
    componentUpdated: function(el, binding) {
        jQuery(el).trigger("chosen:updated");
    }
});

Use it like this:

<select v-model="mymodel" v-chosen="mymodel">...</select>

It works with multiple="multiple" and even with nested state, e.g.:

<select v-model="nested.mymodel" v-chosen="nested.mymodel">...</select>

See the fiddle here: https://jsfiddle.net/tylercollier/bvvvgyp0/5/

I made an update for vue2.

Vue.directive('chosen', {
    selected: null,
    inserted: function (el, binding) {
        selected = binding.value;
        $(el).chosen().change(function(event, change) {
            if(change.hasOwnProperty('selected')) {
                selected.push(change.selected);
            } else {
                selected.splice(selected.indexOf(change.deselected), 1);
            }
        });
    },
    componentUpdated: function(el, binding) {
        selected = binding.value;           
        $(el).trigger("chosen:updated");
    }
});

var vm = new Vue({
   el: '#app',
   data: {
      selected: [],
      cities: [{id: 1, value: "Toronto"}, {id: 2, value: "Orleans"}, {id: 3, value: "Bern"}]
   }
});

See: https://jsfiddle.net/kaktuspalme/zenksm2b/

Code taken from @kaktuspalme answer. It works with non-multiple elements now and only for non-multiple.

 Vue.directive('chosensingle', {

inserted: function (el, binding) {
    var selected = binding.value;

    $(el).chosen().change(function(event, change) {

        if(change.hasOwnProperty('selected')) {
            selected.value = change.selected;                
        } else {
            selected.value  ='';
        }
    });
},
componentUpdated: function(el, binding) {

    $(el).trigger("chosen:updated");
}
});

Comments from @Tyler Collier are taken into account

But be carefully,property you use in v-model should be defined as array , e.g. applicantId: [] otherwise it doesn't work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!