Last active
November 10, 2015 14:25
-
-
Save krzystof/f834ef3fb4209210517e to your computer and use it in GitHub Desktop.
SelectTwo vue component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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