Coding a Simple Textarea Character Counter With Vue
Using vue to code a text area character counter is easy! in a few simple steps you can have one up and working.
These instructions below already assume that your basic HTML and CSS have been set up.
Alternatively, jump straight to my codepen below to review the code.
- Set up vue (find more info on that here)
2. Create your vue instance in your script file and bind it to the relevant div/element in your HTML. In this case I’m binding it to a <div>
with an ID of ‘root’— it will look something like the below.
var '#root' = new Vue({
// options
})
3. Add your data attribute and set it to be an empty string. I have named my data attribute ‘message’.
new Vue ({
el: ‘#root’,
data: {
message: ‘’
}})
4. Bind your data to the <textarea>
in your HTML by using the v-model
directive.
<textarea
v-model="message"
placeholder="type your message here"
name=""
maxlength="50"
cols="30"
rows="10">
</textarea>
5. Create a message counter in your HTML, in this case I have just used a <span>
. Use your data name.length in the mustache syntax {{message.length}}
to bind your data to the DOM.
<span class="message-counter">{{ message.length }} / 50</span>
Voila! you now have a character counter using Vue!
Happy Coding 👏👩💻