1

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.

Adrian kevin
  • 45
  • 1
  • 2
  • 8
  • 1
    Your app selector is wrong to begin with: do you mean `el: '#app'` instead? You should be using `this.modelarea.length` instead of `modelarea.length`. What is `str` referring to? Also, your JS appears to be missing a curly bracket—check your browser console for error messages. – Terry Aug 26 '17 at 23:14
  • On top of that, you are using `v-model` incorrectly: you should be using `v-model="modelarea"`. Read the docs: https://vuejs.org/v2/guide/forms.html – Terry Aug 26 '17 at 23:20

1 Answers1

4

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>
Terry
  • 63,248
  • 15
  • 96
  • 118