将Select2(多项选择)与vue.js结合使用 [英] Using Select2 (multiple selections) with vue.js

查看:862
本文介绍了将Select2(多项选择)与vue.js结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是vue的新手,并在 http://vuejs.org上遵循了他们的自定义指令" /examples/select2.html .

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.

我设置了一个jsfiddle来显示此处提供的代码.

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

指令如下;

 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')
    }

任何帮助将不胜感激.

推荐答案

this.value不能像您期望的那样工作(更多信息,请参见:

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?).

尝试一下(在这里工作的小提琴: https://jsfiddle.net/02rafh8p/):

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' }
        ]
    }
})

这篇关于将Select2(多项选择)与vue.js结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆