Vant—van-field textarea 二次封装 高度自适应并设置最大最小高度

本文档介绍了如何在Vant中对van-field的textarea组件进行二次封装,创建了CommentField.vue组件,实现了高度自适应以及设定最大最小高度的功能。在使用页面上,该组件将提供更便捷的文本输入体验。

在这里插入图片描述

1、components新建CommentField.vue

<template>
  <div class="comment-field-wrap">
    <div class="comment-field__input">
      <van-field
        :value="value"
        placeholder="请输入留言内容"
        rows="1" // 显示为一行的高度
        type="textarea"
        autosize
        maxlength="100"
        @input="$emit('input', $event)" // v-model
      />
    </div>
    <button @click="publishComment">发表</button>
  </div>
</template>
<script>
import { Field } from 'vant'
import { publishComment } from '@api'
export default {
  components: {
    [Field.name]: Field
  },
  props: {
    value: { // 使用该组件时外部传入value值
      type: String,
      default: ''
    }
  },
  data() {
    return {
      params: {
        xxx
      }
    }
  },
  methods: {
    // 发表评论
    publishComment() {
      if (!this.value) {
        this.$toast({ message: '请输入留言内容' })
        return
      }
      publishComment({
        xxx
      }).then((res) => {
        this.$toast({
          type: 'success',
          message: '发表成功',
          onClose: () => {
            this.$emit('publish') // 点击发表按钮发送请求 成功后emit
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.comment-field-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #FFFEFF;
  padding: 14px;
  box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.09);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 3;
  .comment-field__input {
    flex: 1;
    display: flex;
    justify-content: space-between;
    border-radius: 21px;
    overflow: hidden;
    border: 1px solid @auxiliary-color-line;
    margin-right: 30px;
    /deep/ .van-field {
      width: 285px;
      border-radius: 17px;
      display: flex;
      align-items: center;
      padding: 8px 20px;
      background: @auxiliary-color-bg;
      &::after {
        content: none;
      }
      .van-field__control {
        max-height: 72px !important; // 设置最大高度 超出隐藏
      }
    }
  }
  button {
    font-size: @font-size-16;
    color: @font-color-5;
    background: none;
    border: none;
    flex-shrink: 0;
    padding: 0;
  }
}
</style>

2、使用页面

<comment-field
    v-model.trim="word" // trim清空前后空格
    @publish="publishWord" // 发表成功的回调
/>
data() {
    return {
        publishWord() {
        	xxx
            // 提交表单神马
        }    
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值