Vue 2与Jquery选择

Waq*_*qas 1 vue-component vuejs2

尝试使用jquery选择vue,问题是这个插件隐藏了我应用v-model的实际选择,所以当我选择一个值时,vue不会将其识别为select change事件,并且模型值不会更新.

我见过Vue 1的一些解决方案,它不适用于Vue 2

它显示当前值,但不知道如何设置以使模型值发生变化.

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");
Run Code Online (Sandbox Code Playgroud)

Ber*_*ert 11

将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');
  }
})
Run Code Online (Sandbox Code Playgroud)

这是模板中的使用示例:

<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>
Run Code Online (Sandbox Code Playgroud)

小提琴多选.

原始答案

此组件未正确处理多个选择,但将其保留在此处,因为它是已接受的原始答案.

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()))
  }
})
Run Code Online (Sandbox Code Playgroud)

该组件支持v-model.这样您就可以在模板中使用它,如下所示:

<chosen-select v-model='cities'>
  <option value="Toronto">Toronto</option>
  <option value="Orleans">Orleans</option>
</chosen-select>
Run Code Online (Sandbox Code Playgroud)

这是你的小提琴更新.