thinkphp3.2 自定义的vue-select2组件

场景

. vue组建中普通的select2 就不可行了, 这时候需要自定义的vue-select2组件出来
. 因为我的是在组件中调用vue-select2组件 所以需要props双向绑定

分析

. 官方的列子是简单的一个组件 但是没有办法双向通信, 实现的内容也只是简单的select2; 所以功能还是
   需要定制  
. 在使用的thinkphp3.2 所以对vue的支持不是特别友好 

参考链接

https://cn.vuejs.org/v2/examples/select2.html

解决

. 建立文件 select2_template.html 填充内容如下(如果是laravel可以直接使用laravel的组件机制)
. 使用方法
   1.   options  [{id : 1 , text:'涨势'}, {id : 2, text:'涨势2'}, {id : 3, text:'涨势3'}]   这个是展示的内容
   2.  selected   select的name 
   3. description   提示(其实就是不选择这一项的问题)

<select_template :options="list_user_options" :selected.sync="id" description="全部账号"></select_template>

<script type="text/x-template" id="select2-template">
    <select class="form-control">
        <slot></slot>
    </select>
</script>

<script type="text/x-template" id="select-demo-template">
    <select2 :options="options" v-model="selected">
        <option  value="">{{ desc }}</option>
    </select2>
</script>

<script>
    Vue.component('select2', {
        props: ['options', 'value'],
        template: '#select2-template',
        mounted: function () {
            var vm = this
            $(this.$el)
            // init select2
                .select2({data: this.options})
                .val(this.value)
                .trigger('change')
                // emit event on change.
                .on('change', function () {
                    vm.$emit('input', this.value)
                })
        },
        watch: {
            value: function (value) {
                // update value
                $(this.$el)
                    .val(value)
                    .trigger('change')
            },
            options: function (options) {
                // update options
                $(this.$el).empty().select2({data: options})
            }
        },
        destroyed: function () {
            $(this.$el).off().select2('destroy')
        }
    });

    Vue.component('select_template', {
        template: '#select-demo-template',
        props: ['options', 'selected', 'description'],
        computed: {
            desc: function () {
                return this.description ? this.description : '全部';
            }
        },
        watch: {

            // selected 监听器如果发生变化的话  那么需要自定义触发事件,更改父组件的值
            selected: function (selected) {
                // update  value
                this.$emit('update:selected', selected)
            }
        }

        // 需要的属性值如下
        // data : function() {
        //     return  {
        //         selected: 2,
        //             options: [
        //             { id: 1, text: 'Hello'},
        //             { id: 2, text: 'World'}
        //         ]
        // }}
    });

</script>

猜你喜欢

转载自blog.csdn.net/cominglately/article/details/80773597