Reputation: 73
I created a new directive to use select2.js, and I want call a callback parameter inside a change event of select2.
The directive code:
Vue.directive('select', {
twoWay: true,
priority: 1000,
params: ['options', 'change'],
bind: function() {
var self = this;
var vm = this.vm;
var key = this.expression;
$(this.el)
.select2({
data: this.params.options,
theme: "bootstrap",
language: "pt-BR",
containerCssClass: ':all:'
})
.on('change', function() {
self.set($(self.el).val());
self.params.change($(self.el).val());
});
vm.$set(key, $(this.el).val());
},
update: function(value, oldValue) {
$(this.el).val(value).trigger('change');
},
unbind: function() {
$(this.el).off().select2('destroy');
}
});
And using:
<select v-select="controller" change="getActions">
.... options ...
</select>
Solution I found (I do not know if it's the best):
...
.on('change', function() {
self.set($(self.el).val());
if(typeof vm[self.params.change] == 'function') vm[self.params.change]($(self.el).val());
});
...
Upvotes: 2
Views: 7456
Reputation: 5996
Here is a fiddle showing how you can pass a callback using select2 as a component as opposed to a directive.
https://jsfiddle.net/vbranden/up8kb0j8/
Essentially make the "change" prop a functiob
props: {
change: { type: Function }
}
then call it in the change event (im using lodash in my fiddle)
$(self.$el).select2(config).on('select2:select select2:unselect', function () {
if (_.isFunction(self.change)) self.change(v)
})
I used select2 in a vue project recently and had a lot of issues with it as a directive. as a component it works much better IMHO
Upvotes: 3