Vue : Limit characters in text area input, truncate filter? Vue : Limit characters in text area input, truncate filter? vue.js vue.js

Vue : Limit characters in text area input, truncate filter?


This is one of those cases, where you really want to use a component.

Here is an example component that renders a textarea and limits the amount of text.

Please note: this is not a production ready, handle all the corner cases component. It is intended as an example.

Vue.component("limited-textarea", {  props:{    value:{ type: String, default: ""},    max:{type: Number, default: 250}  },  template: `    <textarea v-model="internalValue" @keydown="onKeyDown"></textarea>  `,  computed:{    internalValue: {      get() {return this.value},      set(v){ this.$emit("input", v)}    }  },  methods:{    onKeyDown(evt){      if (this.value.length >= this.max) {        if (evt.keyCode >= 48 && evt.keyCode <= 90) {          evt.preventDefault()          return        }      }    }  }})

This component implements v-model and only emits a change to the data if the length of the text is less than the specified max. It does this by listening to keydown and preventing the default action (typing a character) if the length of the text is equal to or more than the allowed max.

console.clear()Vue.component("limited-textarea", {  props:{    value:{ type: String, default: ""},    max:{type: Number, default: 250}  },  template: `    <textarea v-model="internalValue" @keydown="onKeyDown"></textarea>  `,  computed:{    internalValue: {      get() {return this.value},      set(v){ this.$emit("input", v)}    }  },  methods:{    onKeyDown(evt){      if (this.value.length >= this.max) {        if (evt.keyCode >= 48 && evt.keyCode <= 90) {          evt.preventDefault()          return        }      }    }  }})new Vue({  el: "#app",  data:{    text: ""  }})
<script src="https://unpkg.com/vue@2.4.2"></script><div id="app">  <limited-textarea v-model="text"                     :max="10"                    cols="30"                    rows="10">  </limited-textarea></div>