Skip to content

Instantly share code, notes, and snippets.

@mul14
Forked from jasonlfunk/vue2-select2.js
Last active August 23, 2017 16:03
Show Gist options
  • Save mul14/f28410cc5831710554fdee5d2f1e78ba to your computer and use it in GitHub Desktop.
Save mul14/f28410cc5831710554fdee5d2f1e78ba to your computer and use it in GitHub Desktop.
<select2
v-model="something"
:options="[{ id: 1, text: '', selected: true }]"
multiple
placeholder
></select2>
Vue.component('select2', {
props: ['options', 'value', 'multiple', 'placeholder'],
template: `
<select ref="select" :multiple="multiple" :data-placeholder="placeholder">
<slot></slot>
</select>
`,
mounted: function () {
var vm = this;
$(this.$refs.select)
.select2({ data: this.options })
.on('change', function (ev, args) {
if (!(args && "ignore" in args)) {
vm.$emit('input', $(this).val())
}
});
Vue.nextTick(() => {
$(this.$refs.select)
.val(this.value)
.trigger('change', { ignore: true })
});
},
watch: {
value: function (value, oldValue) {
// update value
$(this.$refs.select)
.val(this.value)
.trigger('change', { ignore: true });
},
options: function (options) {
// update options
$(this.$refs.select).select2({ data: options })
}
},
destroyed: function () {
$(this.$refs.select).off().select2('destroy')
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment