利用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 = '';
}

整個方法就是點擊可添加控件,輸入內容,然後內容就會被追加到選中的複選框數組裏面一起提交到服務器(這裏追加的內容雖然沒有顯示在頁面,但是會和其他選中項一起提交),這樣就實現了用戶可以自定義添加複選框選項,並且添加的選項下次就能展示到數組選項中,就可以直接進行選擇了;

剛開始發表博客,希望能將一些在工作中遇到的問題的解決方法分享給大家,如果給你提供了一點解決思路,請幫我點個贊謝謝,有問題的朋友可以在下方一起溝通交流;

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