vuejs input textarea binding with examples


textarea is a input multi line component in HTML. This is used to input forms in web applications to take input from user.

This can be created in html as follows

<textarea placeholder="Please enter comments"></textarea>

In this article, How to implement textarea two input binding with v-model and input binding, and text area example usage.

Simple TextArea example vuejs

Like any input form control, Textarea values mapped to vue component instance using v-model directive.

Vue provides two way binding using v-model directive which pass data from form input control to/from controller.

In the below vue component

Declared textarea in template of vue component Added v-model to have a two way binding from template to/from script Declared message property which configured in v-model attribute in data function

<template>
  <div class="hello">
    <textarea v-model="message" placeholder="Please add"></textarea>
  </div>
  <span>Comments:</span>
  <p style="white-space: pre-line">{{ message }}</p>
  <br />
</template>

<script>
export default {
  name: "textarea",
  props: {
    message: String,
  },
  data: function () {
    return {
      message: "",
    };
  },
};
</script>

<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

v-model provides two way databinding, The same can be achieved with :value and @input ie.Textarea input binding :value provides read the value from input ie one way binding @input allows to set value to input text area.

This way we can achieve two way binding without v-model

<template>
  <div class="hello">
    <textarea
      :value="message"
      @input="message = $event.target.value"
      rows="10"
      cols="50"
    ></textarea>
  </div>
</template>

<script>
export default {
  name: "textarea",
};
</script>

character count with textarea component in vuejs

This is an example of limiting textarea character count to 100, giving error message if count reaches more than 100. In this example,

-keyup event added with event handler function - characterCount, which is binded using v-on or : syntax

  • defined initial values of an text area properties as well character and pending character count
  • v-model holds data property message for two way binding
  • isError is boolean flag to check count is less than -1 and displays error color red
  • characterCount has a logic of checking character count entered in text area

Here is an complete code:


Output:
vue textarea example two way binding
Similar Posts