问题
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.
I've seen some solution available for Vue 1 that don't work with Vue 2
It's showing the current value but doesn't know how to set so that model value 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:
The preferred method of integrating jQuery plugins into Vue 2 is to wrap them in a component. Here is an example of your Chosen plugin wrapped in a component that handles both single and multiple selects.
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 usage 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 select.
Original Answer
This component doesn't handle multiple selects correctly, but leaving 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 that you can use it in your template like so:
<chosen-select v-model='cities'>
<option value="Toronto">Toronto</option>
<option value="Orleans">Orleans</option>
</chosen-select>
Here is your fiddle updated.
来源:https://stackoverflow.com/questions/44641153/vue-2-with-jquery-chosen