JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://unpkg.com/[email protected]"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/select2.min.css">
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/vue@latest/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-multiple :options="options" v-model="selected">
<option disabled value="0">Select one</option>
</select2-multiple>
<div>
<button @click="selected.push(5)">Add Baz</button>
<button @click="selected = [1,3]">New selected</button>
</div>
</div>
</script>
<script type="text/x-template" id="select2-template">
<select multiple>
<slot></slot>
</select>
</script>
CSS
html, body {
font: 13px/18px sans-serif;
}
select {
min-width: 300px;
}
JavaScript
console.clear()
Vue.component('select2Multiple', {
props: ['options', 'value'],
template: '#select2-template',
mounted: function () {
var vm = this
$(this.$el)
// init select2
.select2({ data: this.options })
.val(this.value)
.trigger('change')
// emit event on change.
.on('change', function () {
vm.$emit('input', $(this).val())
})
},
watch: {
value: function (value) {
if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
$(this.$el).val(value).trigger('change');
},
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: [1],
options: [
{ id: 1, text: 'Hello' },
{ id: 2, text: 'World' },
{ id: 3, text: 'Foo' },
{ id: 4, text: 'Bar' },
{ id: 5, text: 'Baz' },
]
}
});