vue项目中封装一个el-input支持输入标签tag类

<template>
  <!-- 父盒子 -->
  <div class="el-input" @click="onclick">
    <!-- 生成的标签 -->
    <div class="el-select__tags" ref="tags" :style="{ 'max-width': inputWidth - 32 + 'px;width:186px' }">
      <transition-group @after-leave="resetInputHeight">
        <el-tag v-for="(item, index) in TagsAll" :key="index" @close="deleteTag($event, item)" type="primary"
          :closable="true" close-transition>
          <span class="el-select__tags-text" style="
              overflow: hidden;
              text-overflow: ellipsis;
              height: auto;
              word-break: break-all;
              vertical-align: top;
              display: inline-block;
              max-width: 145px;
            ">{{ item }}</span>
        </el-tag>
      </transition-group>
      <!-- 输入框 -->
      <input v-model="currentval" @input="inputChange" @blur="addTags" @keydown.enter.prevent="addTags"
        @keydown.delete="deleteTags" :style="{ width: inputLength + 'px', 'max-width': inputWidth - 42 + 'px' }"
        class="el-select__input" ref="inputTag" type="text" debounce="300" />
    </div>
    <el-input ref="reference" type="text" v-model="ElDateinupt" @keydown.enter.prevent="addTags"
      @keyup.delete.prevent="deleteTags" :placeholder="placeholder">
    </el-input>
  </div>
</template>

<script type="text/babel">
const sizeMap = {
  large: 42,
  small: 30,
  mini: 22,
};
export default {
  name: "inputTags",
  props: {
    switchTags: Boolean,
    value: {
      required: true,
      type: String,
      default() {
        return "";
      }
    },
    placeholder: {
      type: String,
      default() {
        return "请输入按后Enter键生成条件";
      },
    },
  },
  data() {
    return {
      ElDateinupt: "",
      inputWidth: 0,
      //输入框
      currentval: "",
      //tag
      TagsAll: [],
      //输入框宽度
      inputLength: 20,
      //计算删除位置
      n: 0,
    };
  },
  watch: {
    TagsAll() {
      this.$emit("input", this.TagsAll.join(","));
    },
    //监听输入的值越多,输入框越长
    currentval(val) {
      // 实时改变input输入框宽度,防止输入内容超出input默认宽度显示不全
      this.inputLength =this.$refs.inputTag.value.length * 15 + 20;
      this.resetInputHeight()
    },
    value() {
      if (this.value == "") {
        this.TagsAll = [];
      }
    },
    // parentArr() {
    //   this.TagsAll = this.parentArr.length ? this.parentArr : [];
    // },
  },
  computed: {
    //计算属性:计算出动态输入框宽度
    inputStyle() {
      let style = {};
      style.width = `${this.inputLength}px`;
      return style;
    },
    //将生成的数据拼接成字符串,因为我们公司后台需要这种格式的数据。
    // finall() {
    //   return this.TagsAll.join(",");
    // },
  },
  mounted() {
    this.resetInputHeight();
    this.$nextTick(() => {
      if (this.$refs.reference && this.$refs.reference.$el) {
        this.inputLength = this.$refs.inputTag.value.length * 15 + 20;
        this.inputWidth =this.$refs.reference.$el.getBoundingClientRect().width;
      }
    });
  },
  methods: {
    deleteTag(event, tag) {
      let index = this.TagsAll.indexOf(tag);
      if (index > -1) {
        this.TagsAll.splice(index, 1);
      }
      event.stopPropagation();
    },
    inputChange(val) {
      this.resetInputHeight();
    },
    //删除标签时计算input框位置
    resetInputHeight() {
      //console.log("ooo");
      if (this.TagsAll.length == 0 && this.currentval == "") {
        this.ElDateinupt = "";
      } else {
        this.ElDateinupt = " ";
      }
      this.$nextTick(() => {
        if (!this.$refs.reference) return;
        let inputChildNodes = this.$refs.reference.$el.childNodes;
        let input = [].filter.call(
          inputChildNodes,
          (item) => item.tagName === "INPUT"
        )[0];
        const tags = this.$refs.tags;
        input.style.height =
          this.TagsAll.length === 0
            ? (sizeMap[this.size] || 36) + "px"
            : Math.max(
              tags ? tags.clientHeight + 6 : 0,
              sizeMap[this.size] || 36
            ) + "px";
      });
    },
    handleOptionSelect(option) {
      if (this.multiple) {
        const value = this.value.slice();
        const optionIndex = this.getValueIndex(value, option.value);
        if (optionIndex > -1) {
          value.splice(optionIndex, 1);
        } else if (
          this.multipleLimit <= 0 ||
          value.length < this.multipleLimit
        ) {
          value.push(option.value);
        }
        this.$emit("input", value);
        if (option.created) {
          this.query = "";
          this.inputLength = 20;
        }
        if (this.filterable) this.$refs.input.focus();
      } else {
        this.$emit("input", option.value);
        this.visible = false;
      }
      this.$nextTick(() => this.scrollToOption(option));
    },
    //点击叉叉删除tag
    removeTag(index, item) {
      console.log(item);
      this.TagsAll.splice(index, 1);
    },

    //回车增加tag
    addTags() {
      console.log("ppp");
      //新增函数中可以加一些你所需要的校验规则。比如只能是数子,或者不能输入‘,’等
      if (this.currentval) {
        //限制输入长度
        if (this.currentval.length > 200) {
          alert("单标签长度不能超过10个字符!");
        } else {
          //添加tag
          this.TagsAll.push(this.currentval);
          //清空输入框
          this.currentval = "";
          this.$nextTick(() => {
            this.inputLength = this.$refs.inputTag.length * 15 + 20;
            this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
            this.resetInputHeight();
          });
        }
      }
    },

    //键盘删除键删除tag
    deleteTags() {
      //逻辑:当删除到最后一个字符的时候,删除后currentval为空,所以继续执行,n++。这时候n=1.然后判断n是否等于2,不等于不执行。
      //这里是保证当你删除最后一个字符的时候不会执行删除tag的方法,当我们删完了字符后再按一次删除的时候,n就等于2了。就开始删除tag。
      //当有多个tag时,我们连续删除,就会出现,因为currentval为空,所以一直执行n++,导致n不等于2了,所以没法删除后面的tag。
      //所以增加判断,当n大于2的时候我们看tag的长度有没有,有那就继续删除,没有就归0,从来。
      if (this.currentval == "") {
        this.n++;
        if (this.n == 2) {
          this.TagsAll.pop();
        }
        if (this.n > 2) {
          if (this.TagsAll.length) {
            this.TagsAll.pop();
          } else {
            this.n = 0;
          }
        }
      } else {
        this.n = 0;
      }
    },
    //点击父盒子输入框获取焦点
    onclick() {
      this.$nextTick(() => {
        console.log(this.$refs.inputTag);
        this.$refs.inputTag.focus();
      });
    },
  },
};
</script>

<style></style>

参照el-select组件源码进行修改!!!
 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值