/uview-ui/components/加入u-input-tag.vue

调用

<u-form-item label="公司资质" prop="gszz">
                        <u-input-tag v-model="form.gszz" type="tag" placeholder="请输入标签,用逗号或回车分隔"></u-input-tag>
                    </u-form-item>

u-input-tag.vue的代码


<template>

  <view>
    <!-- 标签输入模式 -->
    <view
      v-if="type === 'tag'"
      class="u-input u-input--tag"
      :class="{
        'u-input--border': border,
        'u-input--error': validateState
      }"
      :style="{
        padding: `0 ${border ? 20 : 0}rpx`,
        borderColor: borderColor,
        textAlign: inputAlign
      }"
      @tap.stop="inputClick"
    >
      <!-- 标签容器 -->
      <view class="u-tag-container">
        <!-- 已生成的标签 -->
        <view 
          v-for="(tag, index) in tags" 
          :key="index" 
          class="u-tag"
          :style="{
            backgroundColor: tagBackgroundColor,
            color: tagColor
          }"
        >
          <text class="u-tag-text">{{ tag }}</text>
          <view class="u-tag-close" @tap.stop="removeTag(index)">
            <u-icon name="close" size="16" :color="tagColor" />
          </view>
        </view>
        
        <!-- 输入框 -->
        <input
          ref="tagInput"
          class="u-tag-input"
          :style="[getStyle, { minWidth: tags.length ? '100rpx' : '100%' }]"
          :value="inputValue"
          :placeholder="tags.length ? '' : placeholder"
          :placeholderStyle="placeholderStyle"
          :disabled="disabled"
          :maxlength="inputMaxlength"
          :focus="focus"
          :confirmType="confirmType"
          :cursor-spacing="getCursorSpacing"
          :selection-end="uSelectionEnd"
          :selection-start="uSelectionStart"
          :show-confirm-bar="showConfirmbar"
          :adjust-position="adjustPosition"
          @focus="onFocus"
          @blur="handleBlur"
          @input="handleTagInput"
          @confirm="addTag"
        />
      </view>
    </view>

    <!-- 原始输入模式 -->
    <view
      v-else
      class="u-input"
      :class="{
        'u-input--border': border,
        'u-input--error': validateState
      }"
      :style="{
        padding: `0 ${border ? 20 : 0}rpx`,
        borderColor: borderColor,
        textAlign: inputAlign
      }"
      @tap.stop="inputClick"
    >
      <textarea
        v-if="type == 'textarea'"
        class="u-input__input u-input__textarea"
        :style="[getStyle]"
        :value="defaultValue"
        :placeholder="placeholder"
        :placeholderStyle="placeholderStyle"
        :disabled="disabled"
        :maxlength="inputMaxlength"
        :fixed="fixed"
        :focus="focus"
        :autoHeight="autoHeight"
        :selection-end="uSelectionEnd"
        :selection-start="uSelectionStart"
        :cursor-spacing="getCursorSpacing"
        :show-confirm-bar="showConfirmbar"
        @input="handleInput"
        @blur="handleBlur"
        @focus="onFocus"
        @confirm="onConfirm"
      />
      <input
        v-else
        class="u-input__input"
        :type="type == 'password' ? 'text' : type"
        :style="[getStyle]"
        :value="defaultValue"
        :password="type == 'password' && !showPassword"
        :placeholder="placeholder"
        :placeholderStyle="placeholderStyle"
        :disabled="disabled || type === 'select'"
        :maxlength="inputMaxlength"
        :focus="focus"
        :confirmType="confirmType"
        :cursor-spacing="getCursorSpacing"
        :selection-end="uSelectionEnd"
        :selection-start="uSelectionStart"
        :show-confirm-bar="showConfirmbar"
        :adjust-position="adjustPosition"
        @focus="onFocus"
        @blur="handleBlur"
        @input="handleInput"
        @confirm="onConfirm"
      />
      <view class="u-input__right-icon u-flex">
        <view class="u-input__right-icon__clear u-input__right-icon__item" @tap="onClear" v-if="clearable && value != '' && focused">
          <u-icon size="32" name="close-circle-fill" color="#c0c4cc"/>
        </view>
        <view class="u-input__right-icon__clear u-input__right-icon__item" v-if="passwordIcon && type == 'password'">
          <u-icon size="32" :name="!showPassword ? 'eye' : 'eye-fill'" color="#c0c4cc" @click="showPassword = !showPassword"/>
        </view>
        <view class="u-input__right-icon--select u-input__right-icon__item" v-if="type == 'select'" :class="{
          'u-input__right-icon--select--reverse': selectOpen
        }">
          <u-icon name="arrow-down-fill" size="26" color="#c0c4cc"></u-icon>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import Emitter from '../../libs/util/emitter.js';

export default {
  name: 'u-input-tag',
  mixins: [Emitter],
  props: {
    // ...原有props...
    value: {
        type: [String, Number],
        default: ''
    },
    // 输入框的类型,textarea,text,number
    type: {
        type: String,
        default: 'text'
    },
    inputAlign: {
        type: String,
        default: 'left'
    },
    placeholder: {
        type: String,
        default: '请输入内容'
    },
    disabled: {
        type: Boolean,
        default: false
    },
    maxlength: {
        type: [Number, String],
        default: 140
    },
    placeholderStyle: {
        type: String,
        default: 'color: #c0c4cc;'
    },
    confirmType: {
        type: String,
        default: 'done'
    },
    // 输入框的自定义样式
    customStyle: {
        type: Object,
        default() {
            return {};
        }
    },
    // 如果 textarea 是在一个 position:fixed 的区域,需要显示指定属性 fixed 为 true
    fixed: {
        type: Boolean,
        default: false
    },
    // 是否自动获得焦点
    focus: {
        type: Boolean,
        default: false
    },
    // 密码类型时,是否显示右侧的密码图标
    passwordIcon: {
        type: Boolean,
        default: true
    },
    // input|textarea是否显示边框
    border: {
        type: Boolean,
        default: false
    },
    // 输入框的边框颜色
    borderColor: {
        type: String,
        default: '#dcdfe6'
    },
    autoHeight: {
        type: Boolean,
        default: true
    },
    // type=select时,旋转右侧的图标,标识当前处于打开还是关闭select的状态
    // open-打开,close-关闭
    selectOpen: {
        type: Boolean,
        default: false
    },
    // 高度,单位rpx
    height: {
        type: [Number, String],
        default: ''
    },
    // 是否可清空
    clearable: {
        type: Boolean,
        default: true
    },
    // 指定光标与键盘的距离,单位 px
    cursorSpacing: {
        type: [Number, String],
        default: 0
    },
    // 光标起始位置,自动聚焦时有效,需与selection-end搭配使用
    selectionStart: {
        type: [Number, String],
        default: -1
    },
    // 光标结束位置,自动聚焦时有效,需与selection-start搭配使用
    selectionEnd: {
        type: [Number, String],
        default: -1
    },
    // 是否自动去除两端的空格
    trim: {
        type: Boolean,
        default: true
    },
    // 是否显示键盘上方带有”完成“按钮那一栏
    showConfirmbar:{
        type:Boolean,
        default:true
    },
    // 弹出键盘时是否自动调节高度,uni-app默认值是true
    adjustPosition: {
        type: Boolean,
        default: true
    },
    // 新增标签输入相关props
    tagBackgroundColor: {
      type: String,
      default: '#f0f2f5'
    },
    tagColor: {
      type: String,
      default: '#606266'
    }
  },
  data() {
    return {
      // ...原有data...
      defaultValue: this.value,
      inputHeight: 70, // input的高度
      textareaHeight: 100, // textarea的高度
      validateState: false, // 当前input的验证状态,用于错误时,边框是否改为红色
      focused: false, // 当前是否处于获得焦点的状态
      showPassword: false, // 是否预览密码
      lastValue: '', // 用于头条小程序,判断@input中,前后的值是否发生了变化,因为头条中文下,按下键没有输入内容,也会触发@input时间
      // 标签输入模式相关数据
      tags: [],
      inputValue: '',
      tagInputFocused: false
    };
  },
  watch: {
    // ...原有watch...
    // value(nVal, oVal) {
    //     this.defaultValue = nVal;
    //     // 当值发生变化,且为select类型时(此时input被设置为disabled,不会触发@input事件),模拟触发@input事件
    //     if(nVal != oVal && this.type == 'select') this.handleInput({
    //         detail: {
    //             value: nVal
    //         }
    //     })
    // },
    // 监听value变化,用于标签模式初始化
    value: {
      immediate: true,
      handler(nVal) {
        if (this.type === 'tag' && typeof nVal === 'string' && nVal) {
          // 如果传入的是逗号分隔的字符串,自动转换为标签数组
          this.tags = nVal.split(',').filter(tag => tag.trim());
        }
      }
    }
  },
  computed: {
    // ...原有computed...
    // 因为uniapp的input组件的maxlength组件必须要数值,这里转为数值,给用户可以传入字符串数值
    inputMaxlength() {
        return Number(this.maxlength);
    },
    getStyle() {
        let style = {};
        // 如果没有自定义高度,就根据type为input还是textare来分配一个默认的高度
        style.minHeight = this.height ? this.height + 'rpx' : this.type == 'textarea' ?
            this.textareaHeight + 'rpx' : this.inputHeight + 'rpx';
        style = Object.assign(style, this.customStyle);
        return style;
    },
    //
    getCursorSpacing() {
        return Number(this.cursorSpacing);
    },
    // 光标起始位置
    uSelectionStart() {
        return String(this.selectionStart);
    },
    // 光标结束位置
    uSelectionEnd() {
        return String(this.selectionEnd);
    }
  },
  created() {
    // ...原有created...
    this.$on('on-form-item-error', this.onFormItemError);
  },
  methods: {
    // ...原有方法...
    /**
     * change 事件
     * @param event
     */
    handleInput(event) {
        let value = event.detail.value;
        // 判断是否去除空格
        if(this.trim) value = this.$u.trim(value);
        // vue 原生的方法 return 出去
        this.$emit('input', value);
        // 当前model 赋值
        this.defaultValue = value;
        // 过一个生命周期再发送事件给u-form-item,否则this.$emit('input')更新了父组件的值,但是微信小程序上
        // 尚未更新到u-form-item,导致获取的值为空,从而校验混论
        // 这里不能延时时间太短,或者使用this.$nextTick,否则在头条上,会造成混乱
        setTimeout(() => {
            // 头条小程序由于自身bug,导致中文下,每按下一个键(尚未完成输入),都会触发一次@input,导致错误,这里进行判断处理
            // #ifdef MP-TOUTIAO
            if(this.$u.trim(value) == this.lastValue) return ;
            this.lastValue = value;
            // #endif
            // 将当前的值发送到 u-form-item 进行校验
            this.dispatch('u-form-item', 'on-form-change', value);
        }, 40)
    },
    /**
     * blur 事件
     * @param event
     */
    handleBlur(event) {
        // 最开始使用的是监听图标@touchstart事件,自从hx2.8.4后,此方法在微信小程序出错
        // 这里改为监听点击事件,手点击清除图标时,同时也发生了@blur事件,导致图标消失而无法点击,这里做一个延时
        let value = event.detail.value;
        setTimeout(() => {
            this.focused = false;
        }, 100)
        // vue 原生的方法 return 出去
        this.$emit('blur', value);
        setTimeout(() => {
            // 头条小程序由于自身bug,导致中文下,每按下一个键(尚未完成输入),都会触发一次@input,导致错误,这里进行判断处理
            // #ifdef MP-TOUTIAO
            if(this.$u.trim(value) == this.lastValue) return ;
            this.lastValue = value;
            // #endif
            // 将当前的值发送到 u-form-item 进行校验
            this.dispatch('u-form-item', 'on-form-blur', value);
        }, 40)
    },
    onFormItemError(status) {
        this.validateState = status;
    },
    onFocus(event) {
        this.focused = true;
        this.$emit('focus');
    },
    onConfirm(e) {
        this.$emit('confirm', e.detail.value);
    },
    onClear(event) {
        this.$emit('input', '');
    },
    inputClick() {
        this.$emit('click');
    },
    // 标签输入模式处理
    handleTagInput(event) {
      let value = event.detail.value;
      
      // 检查逗号分隔
      if (value.includes(',')) {
        const parts = value.split(',');
        const newTag = parts[0].trim();
        
        if (newTag) {
          this.tags.push(newTag);
          this.emitTagChange();
        }
        
        // 剩余部分作为输入框内容
        this.inputValue = parts.slice(1).join(',').trim();
      } else {
        this.inputValue = value;
      }
      
      // 触发input事件
      this.$emit('input', this.getTagValue());
    },
    
    // 添加标签(回车或确认时)
    addTag() {
      const value = this.inputValue.trim();
      if (value) {
        this.tags.push(value);
        this.inputValue = '';
        this.emitTagChange();
      }
      
      // 触发confirm事件
      this.$emit('confirm', this.getTagValue());
      
      // 保持输入框焦点
      this.$nextTick(() => {
        this.focusInput();
      });
    },
    
    // 移除标签
    removeTag(index) {
      this.tags.splice(index, 1);
      this.emitTagChange();
      
      // 保持输入框焦点
      this.$nextTick(() => {
        this.focusInput();
      });
    },
    
    // 触发标签变化事件
    emitTagChange() {
      this.$emit('update:tags', [...this.tags]);
      this.$emit('input', this.getTagValue());
      this.dispatch('u-form-item', 'on-form-change', this.getTagValue());
    },
    
    // 获取标签值(逗号分隔的字符串)
    getTagValue() {
      return this.tags.join(',');
    },
    
    // 聚焦输入框
    focusInput() {
      if (this.$refs.tagInput) {
        this.$refs.tagInput.focus();
      }
    },
    
    // 标签输入模式的blur处理
    handleTagBlur(event) {
      const value = event.detail.value.trim();
      if (value) {
        this.tags.push(value);
        this.inputValue = '';
        this.emitTagChange();
      }
      
      this.focused = false;
      this.$emit('blur', this.getTagValue());
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../libs/css/style.components.scss";


.u-input {
    position: relative;
    flex: 1;
    @include vue-flex;

    &__input {
        //height: $u-form-item-height;
        font-size: 28rpx;
        color: $u-main-color;
        flex: 1;
    }

    &__textarea {
        width: auto;
        font-size: 28rpx;
        color: $u-main-color;
        padding: 10rpx 0;
        line-height: normal;
        flex: 1;
    }

    &--border {
        border-radius: 6rpx;
        border-radius: 4px;
        border: 1px solid $u-form-item-border-color;
    }

    &--error {
        border-color: $u-type-error!important;
    }

    &__right-icon {

        &__item {
            margin-left: 10rpx;
        }

        &--select {
            transition: transform .4s;

            &--reverse {
                transform: rotate(-180deg);
            }
        }
    }
}

// 标签输入模式样式
.u-input--tag {
  .u-tag-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 10rpx 0;
    width: 100%;
  }
  
  .u-tag {
    display: inline-flex;
    align-items: center;
    padding: 6rpx 16rpx;
    margin: 4rpx 10rpx 4rpx 0;
    border-radius: 8rpx;
    font-size: 24rpx;
    transition: all 0.2s;
    
    &-text {
      max-width: 200rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    &-close {
      margin-left: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28rpx;
      height: 28rpx;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, 0.1);
    }
  }
  
  .u-tag-input {
    flex: 1;
    min-width: 100rpx;
    height: 50rpx;
    padding: 0;
    margin: 0;
    font-size: 28rpx;
    background: transparent;
    border: none;
    outline: none;
    line-height: normal;
    
    &:focus {
      outline: none;
      box-shadow: none;
    }
  }
}
</style>

点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部