Skip to content

Instantly share code, notes, and snippets.

@krzystof
Last active November 10, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzystof/f834ef3fb4209210517e to your computer and use it in GitHub Desktop.
Save krzystof/f834ef3fb4209210517e to your computer and use it in GitHub Desktop.
SelectTwo vue component
<style>
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 34px;
}
</style>
<template>
<select :class="classes" :multiple="multiselect">
<option value="" v-if="! multiselect"></option>
</select>
</template>
<script>
import $ from 'jquery';
// Require the Select2 plugin including jquery-mouswheel
require('Select2/dist/js/select2.full.min.js');
export default {
props: {
/*
* The classes to pass to the select element.
*
* @type {String}
*/
classes: String,
/*
* The list of options for the select element.
*
* @type {Object}
*/
options: {
required: true
},
/**
* The selected element to initialize.
*
* @type {Object}
*/
selected: {
default: [],
required: false
},
/*
* The select element should use multiselection.
*
* @type {boolean}
*/
multiselect: {
default: false
}
},
computed: {
/*
* The selected values formatted as an array.
*
* @type {Array}
*/
selectedValues() {
return _.isArray(this.selected) ? this.selected : [this.selected];
}
},
ready() {
this.selectElements();
$(this.$el).select2({
data: this.options,
});
},
methods: {
/*
* Select the elements passed as props.
*/
selectElements() {
if (! this.selected) {
return;
}
if (this.hasOptGroup()) {
return _.map(this.options, (optionGrp) => {
this.mapAndSelect(optionGrp.children);
}.bind(this));
}
return this.mapAndSelect(this.options);
},
/*
* Map a Collection and set the selected state for each option.
*/
mapAndSelect(options) {
_.map(options, (option) => {
if (this.selectedValues.indexOf(parseInt(option.id)) !== -1) {
console.log(option);
option.selected = true;
}
}.bind(this));
},
/*
* Check whether the options have a nested level (<optgroup>)
*/
hasOptGroup() {
return _.every(this.options, (option) => {
return _.has(option, 'children');
});
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment