我們經常在使用 Element組件里面的 select多選
場景:添加賬號的時候需要選擇可見分公司(分公司為多選),添加成功之后可以編輯,需要回顯添加時所提交的分公司
代碼如下:
多選框:
data(){ return{
oldSearchJobType: [],
companyIds: "", //分公司數據id companyList: [], //分公司列表 companyListAll: { id: "", visibleCompany: "全部" }, //分公司列表 ruleForm: { company: [], //分公司 }, }}
<el-form-item label="可見分公司:" prop="company"> <el-select v-model="ruleForm.company" multiple collapse-tags @change="changCompany" placeholder="請選擇可見分公司" > <el-option v-for="item in companyList" :key="item.id" :label="item.visibleCompany" :value="item.id" ></el-option> </el-select> </el-form-item>
獲取分工公司接口時:
添加一個全部的選項,拼接到分公司里面去,然后把分公司的id 循環取出來(因為向后台傳輸數據的時候需要傳id)
this.$http
.post("/crm/customer/visibleCompanyList")
.then(response => {
//分公司數據
this.companyList = response.data.result;
this.companyList.unshift(this.companyListAll);
let ids = [];
this.companyList.map(item => {
ids.push(item.id);
this.companyIds = ids;
});
})
.catch(res => {
console.error("請求失敗", res);
});
在點擊編輯時,后台需要返回分公司的名稱及id , 需要這有這樣存起來
let companyArr = []; //分公司
let companyIds = []; //分公司id
companyArr = response.data.result.visibleCompanyNameStr.split(",");
companyIds = response.data.result.visibleCompanyIdStr.split(",");
//給分公司賦值
changCompany(val) {
let allValues = [];
allValues = this.companyIds;
const oldVal =
this.oldSearchJobType.length === 1 ? this.oldSearchJobType[0] : [];
// 若是全部選擇
if (val.includes("")) this.ruleForm.company = allValues;
// 取消全部選中 上次有 當前沒有 表示取消全選
if (oldVal.includes("") && !val.includes("")) this.ruleForm.company = [];
// 點擊非全部選中 需要排除全部選中 以及 當前點擊的選項
// 新老數據都有全部選中
if (oldVal.includes("") && val.includes("")) {
const index = val.indexOf("");
val.splice(index, 1); // 排除全選選項
this.ruleForm.company = val;
}
// 全選未選 但是其他選項全部選上 則全選選上 上次和當前 都沒有全選
if (!oldVal.includes("") && !val.includes("")) {
if (val.length === allValues.length - 1)
this.ruleForm.company = [""].concat(val);
}
// 儲存當前最后的結果 作為下次的老數據
this.oldSearchJobType[0] = this.ruleForm.company;
},
以上代碼就完成了多選編輯回顯的功能,點擊確認編輯的時候
this.ruleForm.company.toString() (轉不轉toString() 具體要看后台的接收方式,字符串就轉,數組就不需要了)