Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

A useful “word count” feature is recommended: Ant Design Vue’s default Textarea component does not have a word count feature, but this feature is common enough to make a simple secondary wrap. In fact, this function is very simple, is not changing the original component of the case, the lower right corner plus a count text, with positioning processing on the line.

The default textarea

Official website: antdv.com/components/…

The basic usage is as follows:

<a-textarea v-model="desc" placeholder="Please enter a description" :auto-size="false" />
Copy the code

Textarea after modification

See $attrs and V-Model for an explanation of encapsulation principles in the previous article

<template>
  <div class="textarea-wrapper">/ / text boxes<a-textarea
      class="m-textarea"
      v-bind="$attrs"
      v-model="$attrs.value"
      @change="onChange"
    />// Word count<span v-if="showWordLimit" class="m-count"
      >{{ textLength }}/<template v-if="$attrs.maxLength"
        >{{ $attrs.maxLength }}</template
      ></span
    >
  </div>
</template>

<script>
  export default {
    props: {
      // Whether to display the word count
      showWordLimit: {
        type: Boolean.default: false,}},/ / v - model processing
    model: {
      prop: "value".event: "change",},computed: {
      // Length control
      textLength() {
        return (this.$attrs.value || "").length; }},methods: {
      onChange(e) {
        // The v-model callback function
        this.$emit("change", e.target.value); ,}}};</script>

<style lang="scss" scoped>
  .textarea-wrapper {
    position: relative;
    display: block;

    .m-textarea {
      padding: 8px 12px;
      height: 100%;
    }

    .m-count {
      color: # 808080;
      background: #fff;
      position: absolute;
      font-size: 12px;
      bottom: 8px;
      right: 12px; }}</style>
Copy the code

It’s easy to use, just like a normal Textarea. To enable word count, both showWordLimit and maxLength must be configured.

<m-textarea
  v-model="desc"
  :showWordLimit="true"
  :maxLength="20"
  :autoSize="false"
  placeholder="Please enter a description"
/>
Copy the code