使用element-ui 自定義複選框組件(允許自定義添加新的選項)

vue組件

<template>
    <div class="main">
        <el-checkbox-group v-model="checkResults" class="check-group">
            <el-checkbox :label="i" name="type" v-for="i in checks"
                         :key="i"></el-checkbox>
        </el-checkbox-group>
        <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
                size="small"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">添加新的</el-button>
    </div>
</template>

<script>
    export default {
        name: "CheckInput",
        data() {
            return {
                inputVisible: false,
                inputValue: '',
                checks: [],
                checkResults: [],
            }
        },
        props: {
            defaultChecks: Array,
            results: {
                type: Array,
                required: true
            },
        },
        created() {
            let dc = this.defaultChecks;
            if (dc) {
                for (let i = 0; i < dc.length; i++) {
                    this.checks.push(dc[i])
                }
            }
        },
        watch: {
            checkResults(n) {
                this.$emit('update:results', n)
            },
        },
        methods: {
            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    if (!this.checks.includes(inputValue)) {
                        this.checks.push(inputValue)
                    }
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(() => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
        },

    }
</script>

<style scoped>
    .main {
        display: inline;
    }

    .button-new-tag {
        color: #70bdff;
        margin-left: 15px;
        height: 25px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 15px;
    }

    .check-group {
        display: inline;
    }

</style>

使用

     <el-form-item label="複選">
             <check-input :default-checks="['默認']" :results.sync="results"></check-input>
      </el-form-item>

效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章