Skip to content

Instantly share code, notes, and snippets.

@Fusseldieb
Last active March 23, 2022 03:19
Show Gist options
  • Select an option

  • Save Fusseldieb/0e2bd6af4579a37cb1dabdd8866a80b5 to your computer and use it in GitHub Desktop.

Select an option

Save Fusseldieb/0e2bd6af4579a37cb1dabdd8866a80b5 to your computer and use it in GitHub Desktop.
A custom select2 component which is ready to be used
<!--
Access it with: <select2 v-model="fields.value" :options="fields.options" :tags="true"></select2>
A object fields exist with following structure:
fields: {
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", but if no "id" is specified, "text" will be used on both. See ternary in template below.
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 supports "options live reloading".
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.
(It does that by destroying, and then recreating the Select2 instance in the nextTick.
This reinitialization is unnoticeable to the human eye.)
-->
<template>
<select :value="value" style="width: 100%">
<option value="" selected disabled>Choose...</option>
<option v-for="(val) in options" :key="val.id">{{val.text}}</option>
</select>
</template>
<script>
import $ from "jquery";
import select2 from "select2";
export default {
name: "Select2",
props: ["options", "value", "ajax", "tags"],
mounted: function() {
var vm = this;
$(this.$el)
// init select2
.select2({ data: this.options, ajax: this.ajax, tags: this.tags })
.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(options) {
// update options
$(this.$el)
.off()
.select2("destroy");
this.$nextTick(function() {
$(this.$el).select2();
});
}
},
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