尝试将 jquery-chosen 与 vue 一起使用,问题是该插件隐藏了我应用 v-model 的实际选择,因此当我选择一个值时,vue 不会将其识别为选择更改事件并且模型值为未更新。
我见过一些适用于 Vue 1 但不适用于 Vue 2 的解决方案
它显示当前值但不知道如何设置以便模型值发生变化。
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");
最佳答案
将 jQuery 插件集成到 Vue 2 中的首选方法是将它们包装在一个组件中。下面是您的 Chosen 插件的一个示例,该插件包装在一个组件中,该组件可以处理单选和多选。
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');
}
})
这是模板中的用法示例:
<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用于多选。
原始答案
此组件无法正确处理多项选择,而是将其保留在这里,因为它是被接受的原始答案。
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()))
}
})
该组件支持v-model。这样您就可以像这样在模板中使用它:
<chosen-select v-model='cities'>
<option value="Toronto">Toronto</option>
<option value="Orleans">Orleans</option>
</chosen-select>
这是你的 fiddle updated .
关于vuejs2 - 选择 Jquery 的 Vue 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641153/