Skip to content

Instantly share code, notes, and snippets.

@Fusseldieb
Last active March 23, 2022 03:19
A custom select2 component which is ready to be used
<!--
Access it with: <select2 v-model="field.value" :options="field.options" :tags="true"></select2>
A object exists with following structure:
field: {
value: "",
options: [
{ id: "0", text: "No" },
{ id: "5", text: "5 mm" },
{ id: "10", text: "10 mm" }
]
}
The "tags" parameter is there to allow the user to write its own text and select it.
In the "options" array, there are "id" and "text".
The "ajax" object is also supported. Just add :ajax="field.ajax" to the HTML tag and put your ajax call inside "field" as "ajax".
Import this component in your view or whatever with:
import Select2 from "@/components/Select2.vue"; (or where the file is)
... Basically an "improved" example of https://vuejs.org/v2/examples/select2.html
EDIT: Now the options are reactive.
If you use a computed property to translate the options (or similar),
this Select2 template will automatically update all options and select the same option again, with the new text Strings.
EDIT2: [BUGFIX] Fixed v-model being destroyed. Now the options are reloaded without destroying and reloading Select2.
-->
<template>
<select :value="value" style="width: 100%"></select>
</template>
<script>
import $ from "jquery";
import select2 from "select2";
export default {
name: "Select2",
props: ["options", "value", "ajax", "tags"],
mounted: function() {
var vm = this;
let options = [];
options.push({
id: "",
text: "Choose...", // Supports vue-i18n, just put 'this.$t('select2.choose')' here
disabled: true,
selected: true
});
options = options.concat(this.options);
$(this.$el)
// init select2
.select2({ ajax: this.ajax, tags: this.tags, data: options })
.val(this.value)
.trigger("change")
// emit event on change.
.on("change", function() {
vm.$emit("input", this.value);
});
},
watch: {
value: function(value) {
// update value
$(this.$el)
.val(value)
.trigger("change");
},
options: function(newoptions) {
let options = [];
options.push({
id: "",
text: "Choose...", // Supports vue-i18n, just put 'this.$t('select2.choose')' here
disabled: true,
selected: true
});
options = options.concat(newoptions);
$(this.$el)
.empty()
.select2({ data: options });
}
},
destroyed: function() {
$(this.$el)
.off()
.select2("destroy");
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment