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="field.value" :options="field.options" :tags="true"></select2>
A object "field" exist with following structure:
field: {
value: "",
options: [
{ value: "0", text: "No" },
{ value: "5", text: "5 mm" },
{ value: "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 "value" and "text", but if no "value" 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-custom.vue"; (or where the file is)
-->
<template>
<select :value="value" style="width: 100%">
<option value="" selected disabled>Choose...</option>
<option v-if="!options">{{ value }}</option>
<option v-for="option in options" :value="option.value ? option.value : option.text">
{{ option.text }}
</option>
</select>
</template>
<script>
import $ from "jquery";
import select2 from "select2";
export default {
name: "Select2",
props: ["value", "options", "tags", "ajax"],
mounted: function() {
const vm = this;
$(vm.$el)
.select2({
tags: vm.tags,
// selectOnClose: true,
ajax: vm.ajax
})
.on("change", function() {
vm.$emit("input", vm.$el.value);
});
},
watch: {
value: function(value) {
$(this.$el)
.val(value)
.trigger("change");
},
options: function(options) {
console.log(options);
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment