利用tag(input)标签实现自定义添加checkbox选项内容;

我们经常会利用一些复选框数组来做一些选择内容,如职位选择,爱好选择;但是可供选择的数组里面可能没有用户需要的选项,这时候我们需要让用户可以自定义添加一个选项内容;然后我们就可以利用elementui中的tag标签来实现一个可添加控件;其实我们并没有实际应用到tag标签,而是用到了他的可动态编辑标签的一个方法;具体代码如下:
在这里插入图片描述
html代码:也可从elementui中tag标签–动态编辑标签中获取(只需要input和button内容,因为我们不需要生成一个tag标签):

<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"></el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput">+可添加</el-button>

css代码:设置添加控件(复制即可):

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

js代码:

data(){
    return {
        proSpylist: [], // 复选框数组数据
        proSpySlectedlist: [], // 被选中的复选框数组
        // tag标签添加
        inputVisible: false,
        inputValue: '', // 这个是你自定义添加的复选框值
    }
},
methods: {
         // 复选框对话框的显示事件
        showEditProSpyDialog() {
            // 加载复选框数组
            this.getProSpylist();
            // 将选中的内容加载出来
            this.proSpySlectedlist = this.proInfoForm.specialty.split(',');
            // 显示对话框
            this.editProSpyDialog = true;
        },
        // 复选框对话框的确认事件
        async editProSpyHandle() {
            const { data: res } = await this.$http.post('updprojectspecialty', {
                userid: this.sessionInfo.userid,
                sid: this.sessionInfo.session,
                projectid: this.sessionInfo.proId,
                specialty: this.proSpySlectedlist // 提交选中的复选框数组
            });
            if (res.code !== 0) {
                return this.message.error('提交失败');
            }
            this.message.success('提交成功');
            // 重新加载页面详情
            this.getProjectInfoById();
            // 关闭对话框
            this.editProSpyDialog = false},  
        // 项目专业选项添加, 下面两个函数可以直接从elementui中方法获取;
        showInput() {
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            const inputValue = this.inputValue;
            if (inputValue) {
                // 重点要将inputValue追加到proSpySlectedlist数组里面,
               	// 这个数组就是提交的选中的复选框数组
                this.proSpySlectedlist.push(inputValue);
            }
            this.inputVisible = false;
            this.inputValue = '';
}

整个方法就是点击可添加控件,输入内容,然后内容就会被追加到选中的复选框数组里面一起提交到服务器(这里追加的内容虽然没有显示在页面,但是会和其他选中项一起提交),这样就实现了用户可以自定义添加复选框选项,并且添加的选项下次就能展示到数组选项中,就可以直接进行选择了;

刚开始发表博客,希望能将一些在工作中遇到的问题的解决方法分享给大家,如果给你提供了一点解决思路,请帮我点个赞谢谢,有问题的朋友可以在下方一起沟通交流;

发布了2 篇原创文章 · 获赞 2 · 访问量 41

猜你喜欢

转载自blog.csdn.net/web9968/article/details/105263251
今日推荐