Skip to content

Instantly share code, notes, and snippets.

@bezborodow
Forked from jasonlfunk/vue2-select2.js
Last active March 7, 2018 13:09
Show Gist options
  • Save bezborodow/55f77b2f867e96b77ba56af71f4ed5b7 to your computer and use it in GitHub Desktop.
Save bezborodow/55f77b2f867e96b77ba56af71f4ed5b7 to your computer and use it in GitHub Desktop.
<template>
<select ref="select">
<option v-if="!this.value"></option>
</select>
</template>
<script>
export default {
props: ['options', 'url', 'placeholder', 'allow_clear', 'label', 'value'],
mounted() {
let config = {
data: this.data,
placeholder: this.placeholder,
allowClear: this.allow_clear || false,
minimumResultsForSearch: 10,
}
if (this.url)
config.ajax = {
url: this.url,
};
var vm = this;
var options = this.options;
let $select = $(this.$refs.select)
.select2(config)
.on('change', function(ev, args) {
if (!(args && "ignore" in args)) {
let input = $(this).val();
if (options)
for (let i = 0; i < options.length; i++) {
let opt = options[i];
if (opt[Object.keys(opt)[0]] == input) {
vm.$emit('input', opt);
break;
}
}
else
vm.$emit('input', input);
}
});
if (this.value)
$select.val(typeof this.value == 'object' ? this.value[Object.keys(this.value)[0]] : this.value)
.trigger('change', { ignore: true });
},
computed: {
data() {
if (!this.options) return null;
let data = [];
for (let i = 0; i < this.options.length; i++) {
let opt = this.options[i];
if (opt.id && opt.text)
data.push(opt);
else if (typeof opt == 'string')
data.push({
id: i + 1,
text: opt,
});
else
data.push({
id: opt[Object.keys(opt)[0]],
text: this.label ? opt[this.label] : opt[Object.keys(opt)[1]],
});
}
return data;
},
},
watch: {
value(value, oldValue) {
// update value
$(this.$refs.select)
.val(typeof this.value == 'object' ? this.value[Object.keys(this.value)[0]] : this.value)
.trigger('change', { ignore: true });
},
options(options) {
// update options
$(this.$refs.select).select2({ data: options })
}
},
destroyed() {
$(this.$refs.select).off().select2('destroy')
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment