Remaining character count in Vue.js

Monday, 04 Jun 2018

Often you'll want to limit the number of characters a user can put into an input field such as a textarea. When you do this it's a good idea to show the number of characters the user has left available in real time to avoid frustration. This is a common practice and something that's really easy to achieve in Vue.js.

Vue component scaffolding

Let's start by scoping out a simple vue component. All that's happening here is we're rendering a HTML textarea where the content is bound to the text data property and where the id, name and label are populated by props. There's a placeholder for the characters remaining message underneath too. We also need a data property to set the max number of characters a user can enter.

Notice the computed property for charactersRemaining which returns the result of the calculation. The property gets reevaluated every time either the max character count or, more likely, the text in the textarea changes. We can display the result by referencing it like a normal data property in the template.

Telling the user when they've gone over

We now have a working countdown of the number of characters remaining as the user types, but what happens when the user goes over? We see a minus number. This is a bit rubbish, so let's add another message which tells them when they've gone over, and by how much.

Here we've added a new computed property which calculates how many characters over the limit the text is. There's also a isOver method which returns a boolean depending on if the user has gone over or not. This is used to toggle the display of the two messages.

Make it configurable

We won't always want to have the same limit for all of our textareas, and we want our component to be reusable, so let's make it configurable.

We've added a new prop for limit and a hook for when the component is mounted. We need to set the maxCharacter data property to the value of the limit prop when the component is initialised. The mounted hook is fired when the component is inserted into the DOM, which is just what we need. It's worth becoming familiar with the Vue instance lifecycle.

Demo time

Well that's it. There's a whole bunch of stuff we could add to make this even better, but that's our basic character counter.