Adrian kevin
Adrian kevin

Reputation: 45

How do i count new lines with vuejs from textarea?

I try to count new lines from textarea with vuejs i have this textarea

<textarea v-model="modelarea" v-on:keyup="show"> </textarea>

vuejs code

    new Vue({
    data:{
       modelarea:''
         },
      methods: {        
      show: function(){
                var length = 0;
                for(var i = 0; i < this.modelarea.length; ++i){
                if(this.modelarea[i] == '\n') {
        length++;
     }
}

      }
    })

and echo it

<label>{{ length }}</label>

But it don't work the function I think is wrong.

Upvotes: 1

Views: 5101

Answers (1)

Terry
Terry

Reputation: 66188

As per my comment, there are several mistakes with your code (based on the first version of your question before you edited it in multiple successions):

  1. Your el value is incorrect. Use #app instead of just app
  2. You are missing a <div id="app"> in your markup, so your app will never by Vue-ified.
  3. You are missing a trailing } somewhere in your code, resulting in a syntax error

With regards to your question, since v-model actually updates the modelarea value live, you do not need to bind additional keyup listener to your <textarea>. What you need is simply a computed property that gets the number of new lines in your modelarea string (this has been addressed in another SO question: How to count the number of lines of a string in javascript). Remember than all these variables/props are reactive :)

In other words, you can simply get along with using el, data and computed, nothing more than that. See proof-of-concept example below:

new Vue({
  el: '#app',
  data: {
    modelarea: ''
  },
  computed: {
    lineCount: function() {
      // Return number of lines using regex if not empty
      return this.modelarea.length ? this.modelarea.split(/\r\n|\r|\n/).length : 0;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <textarea v-model="modelarea"></textarea>
  <span>Number of lines: {{ lineCount }}</span>
</div>

Upvotes: 4

Related Questions