2

I'm new to vue and have followed their 'custom directive' at http://vuejs.org/examples/select2.html.

This works well when only selecting one item, but when you're selecting multiple items it only passes the first one. I need it to pass all values selected.

I have a jsfiddle set up displaying the code which is available here. https://jsfiddle.net/f3kd6f14/1/

The directive is as below;

 Vue.directive('select', {
    twoWay: true,
    priority: 1000,

    params: ['options'],

    bind: function() {
        var self = this
        $(this.el)
                .select2({
                    data: this.params.options
                })
                .on('change', function() {
                    self.set(this.value)
                })
    },
    update: function(value) {
        $(this.el).val(value).trigger('change')
    },
    unbind: function() {
        $(this.el).off().select2('destroy')
    }

Any help would be appreciated.

2 Answers 2

7

this.value doesn't work like you expect when Select2 is in multiple value mode (more info here: Get Selected value from Multi-Value Select Boxes by jquery-select2?).

Try this (working fiddle here: https://jsfiddle.net/02rafh8p/):

Vue.directive('select', {
    twoWay: true,
    priority: 1000,

    params: ['options'],

    bind: function() {
        var self = this
        $(this.el)
                .select2({
                    data: this.params.options
                })
                .on('change', function() {
                    self.set($(self.el).val()) // Don't use this.value
                })
    },
    update: function(value) {
        $(this.el).val(value).trigger('change')
    },
    unbind: function() {
        $(this.el).off().select2('destroy')
    }
})

var vm = new Vue({
    el: '#el',
    data: {
        selected: [], // Result is an array of values.

        roles : [
            { id: 1, text: 'hello' },
            { id: 2, text: 'what' }
        ]
    }
})
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer.. now, how to specify the default selected options?
Just assign your default to selected rather than an empty array.
-1

In Vue 2, to get all select2 values onchange:

Change this:

.on('change', function () {
  self.$emit('input', this.value); // Don't use this.value
});

To this:

.on('change', function () {
  self.$emit('input', $(this).val());
});

1 Comment

This cause an internal infinite loop that ends freezing the app

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.