vue+element 使用el-tag实现单选多选,动态添加删除标签

以下是完整代码,仅供参考:

<template>
  <div class="tagDialog crmDialog">
    <el-dialog
      title="批量更新标签"
      :visible="true"
      width="600px"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      style="text-align:left"
    >
      <el-form
        ref="ruleForm"
        class="defaultForm"
        :model="ruleForm"
        :rules="rules"
      >
        <el-form-item
          :label="
            this.categoryItem.name + '(' + this.optionModeDesc + ')' + ':'
          "
          prop="tag"
          class="formTitle"
        >
          <!-- 多选 -->
          <!-- 可以传给 v-bind:class 一个对象,以动态地切换样式 class -->
          <div class="znlh-tab-select">
            <div class="tag-group" v-if="optionMode != 0">
              <el-tag
                v-for="(tag, index) in tagOptions"
                :key="index"
                @click="handleChecks(tag)"
                :class="{ active: tag.checked }"
                effect="plain"
              >
                {{tag.labelName.length>10?tag.labelName.substring(0,10)+'...':tag.labelName}}
              </el-tag>

              <!-- 多选自定义添加 -->
              <el-tag
                v-for="item in customList"
                :key="item.labelName"
                closable
                effect="plain"
                @click="handleChecks(item)"
                :class="{ active: item.checked }"
                @close="handleClose(item)"
              >
                {{item.labelName.length>10?item.labelName.substring(0,10)+'...':item.labelName}}
              </el-tag>
            </div>
            <!-- 单选 -->
            <div v-else>
              <el-tag
                v-for="(tag, idx) in tagOptions"
                :key="idx"
                @click="handleRadio(1, tag, idx)"
                @close="handleClose(tag)"
                :class="{ active: idx == activeIndex }"
                effect="plain"
              >
                {{tag.labelName.length>10?tag.labelName.substring(0,10)+'...':tag.labelName}}
              </el-tag>

              <!-- 单选自定义添加 -->
              <el-tag
                v-for="(item, index) in customList"
                :key="index"
                closable
                effect="plain"
                @click="handleRadio(2, item, index)"
                :class="{ active: item.length + index == activeIndex }"
                @close="handleClose(item)"
              >
                {{item.labelName.length>10?item.labelName.substring(0,10)+'...':item.labelName}}
              </el-tag>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="value">
          <el-input
            placeholder="自定义标签(最多可输入64个字符)"
            maxlength="64"
            v-model="ruleForm.value"
          >
            <template slot="append">
              <el-button @click="addCustomLabel(ruleForm.value)">添加</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button
          type="primary"
          :loading="submiting"
          @click="submitForm('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import API from "@/apis/merchant/api.js";
export default {
  name: "changeBusiness",
  data() {
    var validateValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入"));
      } else {
        if (this.ruleForm.value !== "") {
          callback();
        }
      }
    };
    return {
      activeIndex: -1,
      showDiyTag: false,
      diyTagName: "",
      loading: false,
      tagOptions: [],
      submiting: false,
      ruleForm: {
        tag: "",
        value: "",
      },
      rules: {
        value: [{ validator: validateValue, trigger: "blur" }],
      },
      customList: [], //自定义标签
      optionMode: "", //单选、多选标识
      categoryData: [], //分类详情数据
      labelCodeList: [], //标签编码
      optionModeDesc: "", //单选多选标示
    };
  },
  components: {},
  props: {
    merchantCodeList: {
      type: Array,
      default: () => [],
    },
    categoryItem: {
      type: Object,
      default: () => {},
    },
  },
  created() {
    this.fetchMerchantTagList();
  },

  methods: {
    //多选
    handleChecks(tag) {
      tag.checked = !tag.checked;
      if (tag.checked == true) {
        this.labelCodeList.push(tag.labelCode);
      } else {
        this.labelCodeList.splice(this.labelCodeList.indexOf(tag.labelCode), 1);
      }
    },

    // 单选选中
    handleRadio(type, tag, index) {
      // console.log("handleRadio",type,tag,index);
      if (type == 1) {
        this.activeIndex = index;
      }
      if (type == 2) {
        this.activeIndex = tag.length + index;
        // console.log("自定义添加activeIndex",this.activeIndex);
      }
      let radio = [];
      radio.push(tag.labelCode);
      this.labelCodeList = [...new Set(radio)];
      // console.log("单选",this.labelCodeList);
    },

    // 删除
    handleClose(tag) {
      let params = { labelCode: tag.labelCode };
      this.$http.post(this.$api.deleteTags, params).then((res) => {
        this.customList.splice(this.customList.indexOf(tag), 1);
        //多选删除自定义标签,如果已选中,需删除labelCodeList中的编码
        if (this.optionMode != 0) {
          this.labelCodeList.splice(
            this.labelCodeList.indexOf(tag.labelCode),
            1
          );
        }
        this.$message.success("删除成功!");
      });
    },

    // 添加自定义标签
    addCustomLabel(val) {
      if (this.ruleForm.value != "") {
        let params = { labelName: val, categoryCode: this.categoryItem.code };
        this.$http.post(this.$api.addTags, params).then((res) => {
          if (res) {
            this.customList.push({
              labelCode: res,
              labelName: val,
              checked: false,
              length: this.tagOptions.length,
            });
            // console.log("customList", this.customList);
            this.$message.success("添加成功!");
            this.ruleForm.value = "";
          }
        });
      } else {
        this.$refs.ruleForm.validateField("value");
        return false;
      }
    },

    // 获取分类详情
    async fetchMerchantTagList() {
      let params = { labelCategoryCode: this.categoryItem.code };
      this.$http.get(this.$api.categoryDetail, params).then((res) => {
        this.categoryData = res;
        this.tagOptions = res.labelList; //选择项
        this.optionMode = res.optionMode;
        this.optionModeDesc = res.optionModeDesc;
        this.tagOptions.forEach((item) => {
          this.$set(item, "checked", false);
        });
      });
    },

    // 提交表单
    submitForm(ruleForm) {
      let that = this;
      // this.$refs[ruleForm].validate((valid) => {
      //   // console.log('valid = ' + JSON.stringify(valid))
      //   if (valid) {
      //     // console.log(valid);
      that.batchUpdateTag();
      // } else {
      //   // console.log("提交失败,请刷新页面后重试!");
      //   return false;
      // }
      // });
    },
    async batchUpdateTag() {
      // optionMode为0是单选
      if (this.optionMode == 0) {
        if (this.labelCodeList.length > 0) {
          let params = {
            categoryCode: this.categoryItem.code, //商户类别
            labelCodeList: this.labelCodeList, //选中的标签
            merchantCodeList: this.merchantCodeList, //商户
          };
          this.submiting = true;
          this.$http.post(this.$api.updateMerchantTags, params).then((res) => {
            this.submiting = false;
            let count = this.merchantCodeList.length;
            this.$message.success(`更新成功,共更新${count}个商户的标签`);
            this.$emit("close");
            this.$emit("update");
          });
        } else {
          this.$message.error("请选择标签值!");
          return false;
        }
      }

      //多选
      if (this.optionMode == 1) {
        if (this.labelCodeList.length > 0) {
          let params = {
            categoryCode: this.categoryItem.code, //商户类别
            labelCodeList: this.labelCodeList, //选中的标签
            merchantCodeList: this.merchantCodeList, //商户
          };
          this.submiting = true;
          this.$http.post(this.$api.updateMerchantTags, params).then((res) => {
            this.submiting = false;
            let count = this.merchantCodeList.length;
            this.$message.success(`更新成功,共更新${count}个商户的标签`);
            this.$emit("close");
            this.$emit("update");
          });
        } else {
          this.$confirm(
            `尚未选择标签值,提交后将清空所选商户的${this.categoryItem.name}标签值`,
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              let params = {
                categoryCode: this.categoryItem.code, //商户类别
                labelCodeList: this.labelCodeList, //选中的标签
                merchantCodeList: this.merchantCodeList, //商户
              };
              this.submiting = true;
              this.$http
                .post(this.$api.updateMerchantTags, params)
                .then((res) => {
                  this.submiting = false;
                  let count = this.merchantCodeList.length;
                  this.$message.success(`更新成功,共更新${count}个商户的标签`);
                  this.$emit("close");
                  this.$emit("update");
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        }
      }
    },
    modalClose() {
      this.$emit("close");
    },
    cancel() {
      this.$emit("close");
    },
    showTip(message) {
      this.$message({ message: message, type: "error" });
    },
  },
};
</script>

<style lang="less" >
.tagDialog {
  .el-dialog__header {
    text-align: left;
    background-color: #243042;
    padding: 15px 20px;
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__headerbtn {
      top: 15px;
      right: 15px;
      font-size: 24px;
      .el-dialog__close {
        color: #ffffff;
      }
    }
  }
  .el-dialog__body {
    padding-left: 30px;
    padding-right: 60px;
    background-color: #f8f8f8;
    border-bottom: 1px solid #c0c4cc;
    .el-form {
      margin-left: 18px;
      // .el-form-item__label {
      //   line-height: 25px;
      // }
      .formTitle {
        display: flex;
        .el-form-item__label {
        color: #333333;
        }
      }

      .znlh-tab-select {
        width: 345px;
        // float: left;
        .el-tag--plain {
          color: black;
          border-color: #efefef;
          margin-right: 10px;
        }
        .active {
          color: #3e79ff;
          background-color: #ecf5ff;
          border: 1px solid #9eb5ed;
        }
      }
    }
    .areastyle {
      display: inline-block;
    }
    .areastyle + .areastyle .el-form-item__content {
      margin-left: 8px !important;
    }
  }
  .el-dialog__footer {
    background-color: #f8f8f8;
  }
}
</style>

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Vue+ElementUI中使用el-select组件进行单选多选时,可以通过设置v-model来绑定选中的值,并且根据el-select组件的multiple属性来决定是单选还是多选单选时,v-model绑定的是一个普通变量,当用户选择一个选项时,v-model变量会被更新为选中的值。例如: ``` <el-select v-model="selectedItem"> <el-option label="选项1" value="option1"></el-option> <el-option label="选项2" value="option2"></el-option> <el-option label="选项3" value="option3"></el-option> <el-option label="选项4" value="option4"></el-option> </el-select> ``` 其中,`selectedItem`是一个普通变量,用来保存选中的值。当用户选择一个选项时,`selectedItem`变量会自动更新。 多选时,v-model绑定的是一个数组,用来保存选中的值。例如: ``` <el-select v-model="selectedItems" multiple> <el-option label="选项1" value="option1"></el-option> <el-option label="选项2" value="option2"></el-option> <el-option label="选项3" value="option3"></el-option> <el-option label="选项4" value="option4"></el-option> </el-select> ``` 其中,`selectedItems`是一个数组,用来保存选中的值。当用户选择一个或多个选项时,`selectedItems`数组会自动更新。 要回显已选中的值,只需要将v-model绑定的变量或数组初始化为已选中的值即可。例如: 单选回显: ``` <template> <el-select v-model="selectedItem"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option> </el-select> </template> <script> export default { data() { return { selectedItem: "option2", // 已选中的值 options: [ { label: "选项1", value: "option1" }, { label: "选项2", value: "option2" }, { label: "选项3", value: "option3" }, { label: "选项4", value: "option4" }, ], }; }, }; </script> ``` 多选回显: ``` <template> <el-select v-model="selectedItems" multiple> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option> </el-select> </template> <script> export default { data() { return { selectedItems: ["option2", "option4"], // 已选中的值 options: [ { label: "选项1", value: "option1" }, { label: "选项2", value: "option2" }, { label: "选项3", value: "option3" }, { label: "选项4", value: "option4" }, ], }; }, }; </script> ``` 在上面的例子中,`selectedItem`变量或`selectedItems`数组被初始化为已选中的值,因此在页面加载时,已选中的选项会被自动回显。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值