Select2和Vue Directive

时间:2016-04-23 09:41:04

标签: javascript jquery vue.js select2 vue-resource

我正在通过将jQuery select2插件包装在自定义指令中来集成它。

export default {

    data() {
        return {
            selected: null,
            options: []
        }
    },

    ready() {
    this.fetchUsers()
}

    methods: {
        fetchUsers: function () {
            this.$http({
                url: '/api/users/get-all',
                method: 'GET'
            }).then(function (response) {
                this.$set('options', response.data)
            }, function (response) {
                // error callback
            });
        }
    },

    directives: {
        select: {
            twoWay: true,
            priority: 1000,

            params: ['options'],

            bind: function () {
                var self = this;

                $(this.el)
                        .select2({
                            theme: "bootstrap",
                            closeOnSelect: true,
                            minimumInputLength: 3,
                            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')
            }
        }
    }

}

和HTML:

<select v-select="selected" :options="options"></select>

我尝试获取所有用户并设置为fetchUsers函数中的选项,但似乎fetchUsers函数在select2指令后执行,因此options变量始终为空。

那么如何让所有用户通过ajax(vue-resource)并在填充后选择2?

1 个答案:

答案 0 :(得分:1)

我在select2中遇到了类似的问题,并且必须使用paramwatchers来检查选项何时更新:

select: {
    twoWay: true,
    priority: 1000,

    params: ['options'],

    paramswatchers: {
         "options": function (val, oldVal) {
             $(this.el).select2({
                 data: val
             })
         }
    }

    bind: function () {
        var self = this;

        $(this.el).select2({
            theme: "bootstrap",
            closeOnSelect: true,
            minimumInputLength: 3,
            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')
    }
}

来源:https://vuejs.org/guide/custom-directive.html#params