Vue 2 with Jquery Chosen

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

I saw some solution for Vue 1 that does not work with Vue 2

Shows the current value, but does not know how to set so that the value of the model changes.

http://jsfiddle.net/q21ygz3h/

Vue.directive('chosen', { twoWay: true, // note the two-way binding bind: function(el, binding, vnode) { Vue.nextTick(function() { $(el).chosen().on('change', function(e, params) { alert(el.value); }.bind(binding)); }); }, update: function(el) { // note that we have to notify chosen about update // $(el).trigger("chosen:updated"); } }); var vm = new Vue({ data: { cities: '' } }).$mount("#search-results"); 
+1
vuejs2 vue-component
source share
1 answer

The preferred way to integrate jQuery plugins in Vue 2 is to wrap them in a component. Below is an example of your Chosen plugin wrapped in a component that handles both single and multiple options.

 Vue.component("chosen-select",{ props:{ value: [String, Array], multiple: Boolean }, template:`<select :multiple="multiple"><slot></slot></select>`, mounted(){ $(this.$el) .val(this.value) .chosen() .on("change", e => this.$emit('input', $(this.$el).val())) }, watch:{ value(val){ $(this.$el).val(val).trigger('chosen:updated'); } }, destroyed() { $(this.$el).chosen('destroy'); } }) 

And this is an example of use in a template:

 <chosen-select v-model='cities' multiple> <option value="Toronto">Toronto</option> <option value="Orleans">Orleans</option> <option value="Denver">Denver</option> </chosen-select> <chosen-select v-model='cities2'> <option value="Toronto">Toronto</option> <option value="Orleans">Orleans</option> <option value="Denver">Denver</option> </chosen-select> 

Fiddle for multiple choice.

Original answer

This component does not handle multiple samples correctly, but left it here because it was the original answer that was accepted.

 Vue.component("chosen-select",{ props:["value"], template:`<select class="cs-select" :value="value"><slot></slot></select>`, mounted(){ $(this.$el) .chosen() .on("change", () => this.$emit('input', $(this.$el).val())) } }) 

This component supports v-model. So you can use it in your template like this:

 <chosen-select v-model='cities'> <option value="Toronto">Toronto</option> <option value="Orleans">Orleans</option> </chosen-select> 

Here is your script updated .

+4
source share

All Articles