vuejs2 - 选择 Jquery 的 Vue 2

标签 vuejs2 vue-component

尝试将 jquery-chosen 与 vue 一起使用,问题是该插件隐藏了我应用 v-model 的实际选择,因此当我选择一个值时,vue 不会将其识别为选择更改事件并且模型值为未更新。

我见过一些适用于 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");

最佳答案

将 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/

相关文章:

javascript - 如何根据组件类型过滤 Vue 中的子组件?

javascript - 如何在 Vuetify 文本字段中上标标签

javascript - VueJS : Fetch data before and after loading a component

typescript - 使用 Typescript 在 Vue 数据对象中设置数据类型

javascript - 在 Vue 代码中使用 javascript 库/插件

vue.js - 如果在日期选择器 vuetify 中选择日期,如何调用方法?

vuejs2 - 如何使用 Vue.js 从单个文件组件中的方法访问计算属性

arrays - vue v-if 无法访问数组中的 bool 值

javascript - v-for 的 VueJS forceUpdate 不工作

javascript - Vue 插件,添加获取数据的全局组件