javascript - 使用 Select2 Multiple - 与 vueJS2

标签 javascript vue.js jquery-select2

有没有什么好方法可以使用 Select2 插件通过 VuesJS2 选择多个字段

我找到了这个

https://v2.vuejs.org/v2/examples/select2.html

但这只是单个选择,但我不知道如何将其带到多个选择并输出所选项目的数组。

Vue.component('select2', {
  props: ['options', 'value'],
  template: '#select2-template',
  mounted: function () {
    var vm = this
    $(this.$el)
      .val(this.value)
      // init select2
      .select2({ data: this.options })
      // emit event on change.
      .on('change', function () {
        //vm.$emit('input', this.value)
        //vm.$emit('input', this.value)
        vm.$emit('input', this.value)
      })
  },
  watch: {
    value: function (value) {
      // update value
      $(this.$el).select2('val', value)
    },
    options: function (options) {
      // update options
      $(this.$el).select2({ data: options })
    }
  },
  destroyed: function () {
    $(this.$el).off().select2('destroy')
  }
})

var vm = new Vue({
  el: '#el',
  template: '#demo-template',
  data: {
    selected: [],
    options: [
      { id: 1, text: 'Hello' },
      { id: 2, text: 'World' }
    ]
  }
})
html, body {
  font: 13px/18px sans-serif;
}
select {
  min-width: 300px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://unpkg.com/select2@4.0.3/dist/css/select2.min.css">
<script src="https://unpkg.com/select2@4.0.3"></script>
<script src="https://unpkg.com/vue@2.1.6/dist/vue.js"></script>

<div id="el"></div>

<!-- using string template here to work around HTML <option> placement restriction -->
<script type="text/x-template" id="demo-template">
  <div>
    <p>Selected: {{ selected }}</p>
    <select2 :options="options" v-model="selected">
      <option disabled value="0">Select one</option>
    </select2>
  </div>
</script>

<script type="text/x-template" id="select2-template">
  <select>
    <slot></slot>
  </select>
</script>

最佳答案

我今天偶然发现了这个确切的问题,我只是想发布答案,以防其他人也有同样的疑问。

当从 select2 发出时,您必须使用正确的方法从 select2 中挑选结果。

替换

vm.$emit('input', this.value)

vm.$emit('input',  $(this).val())

这确保我们使用 jquThis 将使用包含所有选定 id 的数组填充 v-model(在您的示例中:selected)。

关于javascript - 使用 Select2 Multiple - 与 vueJS2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243627/

相关文章:

javascript - 如何点击div下的元素?

javascript - 每次点击都会将其功能的性能提高一倍

php - Symfony Form Select2 允许用户输入新值

javascript - 与多个 Select2 绑定(bind)的 Knockout.js

javascript - JQuery 数组项目不是最后一个

javascript - jQuery 表单提交不会返回 false

javascript - 尝试使用转义的单引号解析JSON时Javascript中的“Unexpected identifier”错误

vue.js - 如何使用 v-model 设置输入 Vue 组件的初始值

unit-testing - vue.js 单元测试 - 安装钩子(Hook)错误

jquery - polymer select2元件