Vue3文本域(Textarea)

简介: 这是一个基于 Vue3 的可自定义文本域组件 (`Textarea`),具备多种实用功能,如自适应内容高度、清除图标、字数统计及禁用状态等。

效果如下图:在线预览

在这里插入图片描述

APIs

Textarea

参数 说明 类型 默认值
width 文本域宽度,单位 px string | number ‘100%’
allowClear 可以点击清除图标删除内容 boolean false
autoSize 自适应内容高度 boolean | {minRows?: number, maxRows?: number} false
disabled 是否禁用 boolean false
maxlength 文字最大长度 number undefined
showCount 是否展示字数 boolean false
value v-model 文本域内容 string undefined

Events

事件名称 说明 参数
change 文本域内容变化时的回调 (e: Event) => void
enter 按下回车的回调 (e: Event) => void

创建文本域组件Textarea.vue

<script setup lang="ts">
defineOptions({
  inheritAttrs: false
})
import { ref, computed, watch, onMounted, nextTick } from 'vue'
interface Props {
  width?: string | number // 文本域宽度,单位 px
  allowClear?: boolean // 可以点击清除图标删除内容
  autoSize?: boolean | { minRows?: number; maxRows?: number } // 自适应内容高度
  disabled?: boolean // 是否禁用
  maxlength?: number // 文字最大长度
  showCount?: boolean // 是否展示字数
  value?: string // (v-model) 文本域内容
  valueModifiers?: object // 用于访问组件的 v-model 上添加的修饰符
}
const props = withDefaults(defineProps<Props>(), {
  width: '100%',
  allowClear: false,
  autoSize: false,
  disabled: false,
  maxlength: undefined,
  showCount: false,
  value: '',
  valueModifiers: () => ({})
})
const textareaWidth = computed(() => {
  if (typeof props.width === 'number') {
    return props.width + 'px'
  }
  return props.width
})
const autoSizeProperty = computed(() => {
  if (typeof props.autoSize === 'object') {
    const style: { 'min-height'?: string; 'max-height'?: string; [propName: string]: any } = {
      resize: 'none'
    }
    if ('minRows' in props.autoSize) {
      style['min-height'] = (props.autoSize.minRows as number) * 22 + 10 + 'px'
    }
    if ('maxRows' in props.autoSize) {
      style['max-height'] = (props.autoSize.maxRows as number) * 22 + 10 + 'px'
    }
    return style
  }
  if (typeof props.autoSize === 'boolean') {
    if (props.autoSize) {
      return {
        'max-height': '9000000000000000px',
        resize: 'none'
      }
    }
    return {}
  }
})
const showClear = computed(() => {
  return !props.disabled && props.allowClear && props.value
})
const showCountNum = computed(() => {
  if (props.maxlength) {
    return props.value.length + ' / ' + props.maxlength
  }
  return props.value.length
})
const lazyTextarea = computed(() => {
  return 'lazy' in props.valueModifiers
})
watch(
  () => props.value,
  () => {
    if (JSON.stringify(autoSizeProperty.value) !== '{}') {
      areaHeight.value = 32
      nextTick(() => {
        getAreaHeight()
      })
    }
  },
  {
    flush: 'post'
  }
)
const textarea = ref()
const areaHeight = ref(32)
onMounted(() => {
  getAreaHeight()
})
function getAreaHeight() {
  areaHeight.value = textarea.value.scrollHeight + 2
}
const emits = defineEmits(['update:value', 'change', 'enter'])
function onInput(e: InputEvent) {
  if (!lazyTextarea.value) {
    emits('update:value', (e.target as HTMLInputElement).value)
    emits('change', e)
  }
}
function onChange(e: InputEvent) {
  if (lazyTextarea.value) {
    emits('update:value', (e.target as HTMLInputElement).value)
    emits('change', e)
  }
}
function onKeyboard(e: KeyboardEvent) {
  emits('enter', e)
  if (lazyTextarea.value) {
    textarea.value.blur()
    nextTick(() => {
      textarea.value.focus()
    })
  }
}
function onClear() {
  emits('update:value', '')
  textarea.value.focus()
}
</script>
<template>
  <div
    class="m-textarea"
    :class="{ 'show-count': showCount }"
    :style="`width: ${textareaWidth};`"
    :data-count="showCountNum"
  >
    <textarea
      ref="textarea"
      type="hidden"
      class="u-textarea"
      :class="{ 'textarea-disabled': disabled }"
      :style="[`height: ${autoSize ? areaHeight : ''}px`, autoSizeProperty]"
      :value="value"
      :maxlength="maxlength"
      :disabled="disabled"
      @input="onInput"
      @change="onChange"
      @keydown.enter="onKeyboard"
      v-bind="$attrs"
    />
    <span v-if="showClear" class="m-clear" @click="onClear">
      <svg
        class="clear-svg"
        focusable="false"
        data-icon="close-circle"
        width="1em"
        height="1em"
        fill="currentColor"
        aria-hidden="true"
        viewBox="64 64 896 896"
      >
        <path
          d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-.3L512 563.4l-99.3 118.4-66.1.3c-4.4 0-8-3.5-8-8 0-1.9.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 01-1.9-5.2c0-4.4 3.6-8 8-8l66.1.3L512 464.6l99.3-118.4 66-.3c4.4 0 8 3.5 8 8 0 1.9-.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z"
        ></path>
      </svg>
    </span>
  </div>
</template>
<style lang="less" scoped>
.m-textarea {
  position: relative;
  display: inline-block;
  .u-textarea {
    width: 100%;
    min-width: 0;
    min-height: 32px;
    max-width: 100%;
    height: auto;
    padding: 4px 11px;
    color: rgba(0, 0, 0, 0.88);
    font-size: 14px;
    line-height: 1.5714285714285714;
    list-style: none;
    transition:
      all 0.3s,
      height 0s;
    resize: vertical;
    position: relative;
    display: inline-block;
    vertical-align: bottom;
    text-overflow: ellipsis;
    background-color: #ffffff;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    outline: none;
    &:hover {
      border-color: #4096ff;
      border-inline-end-width: 1px;
      z-index: 1;
    }
    &:focus-within {
      border-color: #4096ff;
      box-shadow: 0 0 0 2px rgba(5, 145, 255, 0.1);
      border-inline-end-width: 1px;
      outline: 0;
    }
  }
  textarea:disabled {
    color: rgba(0, 0, 0, 0.25);
  }
  textarea::-webkit-input-placeholder {
    color: rgba(0, 0, 0, 0.25);
  }
  textarea:-moz-placeholder {
    color: rgba(0, 0, 0, 0.25);
  }
  textarea::-moz-placeholder {
    color: rgba(0, 0, 0, 0.25);
  }
  textarea:-ms-input-placeholder {
    color: rgba(0, 0, 0, 0.25);
  }
  .m-clear {
    position: absolute;
    inset-block-start: 8px;
    inset-inline-end: 8px;
    z-index: 1;
    display: inline-block;
    line-height: 0;
    .clear-svg {
      display: inline-block;
      fill: rgba(0, 0, 0, 0.25);
      font-size: 12px;
      line-height: 1;
      vertical-align: -1px;
      cursor: pointer;
      transition: color 0.3s;
      transition: fill 0.3s;
      &:hover {
        fill: rgba(0, 0, 0, 0.45);
      }
    }
  }
  .textarea-disabled {
    color: rgba(0, 0, 0, 0.25);
    background-color: rgba(0, 0, 0, 0.04);
    cursor: not-allowed;
    &:hover {
      border-color: #d9d9d9;
    }
    &:focus-within {
      border-color: #d9d9d9;
      box-shadow: none;
    }
  }
}
.show-count {
  &::after {
    color: rgba(0, 0, 0, 0.45);
    white-space: nowrap;
    content: attr(data-count);
    pointer-events: none;
    float: right;
  }
}
</style>

在要使用的页面引入

其中引入使用了以下组件:

<script setup lang="ts">
import Textarea from './Textarea.vue'
import { ref, watchEffect } from 'vue'
const value = ref('')
const lazyValue = ref('')
watchEffect(() => {
  console.log('value:', value.value)
})
watchEffect(() => {
  console.log('lazyValue:', lazyValue.value)
})
function onChange(e: Event) {
  console.log('change e:', e, lazyValue.value)
}
function onEnter(e: KeyboardEvent) {
  console.log('enter e:', e, lazyValue.value)
}
</script>
<template>
  <div>
    <h1>{
  { $route.name }} {
  { $route.meta.title }}</h1>
    <h2 class="mt30 mb10">基本使用</h2>
    <Space vertical>
      <Alert>
        <template #message>
          .lazy:
          <br/>
          默认情况下,v-model 会在每次 input 事件后更新数据 (IME 拼字阶段的状态例外)。
          <br />
          你可以添加 lazy 修饰符来改为在每次 change 事件后更新数据:
          <br/>
          {
  { '<Textarea v-model.lazy="msg" />' }}
        </template>
      </Alert>
      <Textarea v-model:value="value" placeholder="Basic usage rows 2" :rows="2" @change="onChange" @enter="onEnter" />
      <Textarea
        v-model:value.lazy="lazyValue"
        placeholder="Lazy usage rows 2"
        :rows="2"
        @change="onChange"
        @enter="onEnter"
      />
    </Space>
    <h2 class="mt30 mb10">适应文本高度的文本域</h2>
    <Space vertical :width="300">
      <Textarea v-model:value="value" placeholder="Autosize height based on content lines" auto-size />
    </Space>
    <h2 class="mt30 mb10">设置行数</h2>
    <Space vertical :width="300">
      <Textarea
        v-model:value="value"
        placeholder="Autosize height with minimum and maximum number of lines"
        :auto-size="{ minRows: 2, maxRows: 5 }"
      />
    </Space>
    <h2 class="mt30 mb10">带移除图标</h2>
    <Space vertical :width="300">
      <Textarea v-model:value="value" placeholder="textarea with clear icon" allow-clear />
    </Space>
    <h2 class="mt30 mb10">带数字提示</h2>
    <Space vertical :width="300">
      <Textarea v-model:value="value" placeholder="textarea with show count" show-count :maxlength="10" />
    </Space>
    <h2 class="mt30 mb10">禁用</h2>
    <Space vertical :width="300">
      <Textarea v-model:value="value" placeholder="disabled textarea" disabled />
    </Space>
  </div>
</template>
相关文章
|
8月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
1079 139
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
1372 5
|
8月前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
566 1
|
9月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
1016 11
|
8月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
645 0
|
10月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
1057 1
|
10月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
521 0
|
11月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
252 0
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
1229 17
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点

热门文章

最新文章