vue--自定义带clearable属性的文本域input组件

今天写页面时遇到一个需求:input框类型是textarea,且支持清除。兴冲冲的直接用以下方式试了一下:

<el-input v-model="val" clearable :rows="5" type="textarea"/>

发现输入框右侧并不会出现清除符号,查了半天发现clearable属性和在type="textarea"时会失效,于是自己封装了一个支持清空的文本域输入框组件,拿来即用!

<template>
  <div class="textInput">
    <el-input
      :rows="rows"
      :placeholder="placeholder"
      v-model="localValue"
      @change="inputChange"
      type="textarea"/>
    <i
      v-show="clearable && localValue"
      class="clearButton el-input__icon el-icon-circle-close el-input__clear"
      @click.prevent="localValue=''"
    />
  </div>
</template>

<script>
export default {
name: "ClearableTextInput",
  props: {
    values: {
      type: String,
      default: function() {
        return ''
      }
    },
    placeholder: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    rows: {
      type: Number,
      default: 1
    },
    inputChange: {
      type: Function,
      default: null
    },
  },
  computed: {
    localValue: {
      get() {
        return this.values;
      },
      set(value) {
        this.$emit('input', value)
      }
    }
  },

}
</script>

<style lang="scss" scoped>
  .textInput {
    position: relative;

    .clearButton {
      position: absolute;
      border-radius: 5px;
      right: 3px;
      z-index: 2;
      border: none;
      top: -3px;
      height: 40px;
      cursor: pointer;
      color: #ccc;
      transform: translateX(2px);
    }

    .clearButton:hover {
      color: #878d99;
    }
  }
</style>

使用示例:

<template>
<div>
    <ClearableTextInput
      :rows="5"
      :placeholder="placeholder"
      v-model="values"
      :values="values"
      :clearable="true"
      :input-change="inputChangeMethod"
    />
</div>
</template>

<script>
export default {
  name: "index",
  components: {
    'ClearableTextInput': resolve => require([('xxxx/ClearableTextInput')], resolve)
  },
  data() {
    return {
      values: '',
      placeholder: 'this is a demo'
    }
  },
  methods: {
   inputChangeMethod() {
     console.log('input changed')
   }
 }   
}
</script>

<style lang="scss" scoped>

</style>

效果:

 

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页