vue element select多选回显

我们经常在使用 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() 具体要看后台的接收方式,字符串就转,数组就不需要了)

 

posted @ 2019-09-29 09:41  傲似小仙女  阅读(20139)  评论(0编辑  收藏  举报