Search code examples
javascripthtmlvue.jsv-for

Page refreshes (unwanted) when method is called


I am trying to dynamically genenrate more input fields using vuejs when the user clicks a button. My code works very briefly (generating more fields), but for some reason after that, the page refreshes automatically, setting the user back to where they started. This is my code

<div class='wordsdiv'>
     <div id='onedictspec' v-for='arrayspot in wordupload.wordinput.length'>
         <input type='text' class='inputwordtext' v-model='wordupload.wordinput[arrayspot - 1][0]'>
         <input type='text' class='inputwordtext' v-model='wordupload.wordinput[arrayspot - 1][1]'>
     </div>
</div>
<div id='morewords'>
    <button class='morewordsbtn active hover' v-on:click='morewords'>More words</button>
</div>

And this is my javascript inside Vue, data

  wordupload: {
      wordinput: [['','']]
 }

And the method

 morewords: function () {
  oldcount = this.wordupload.wordinput.length
  newcount = oldcount + 10
  while (oldcount <  newcount){
    this.wordupload.wordinput.push(["", ""])
    oldcount += 1
  }
}

Basically two input fields are generated for every item in the wordupload.wordinput list, so I try to make more fields by adding more items to wordinput. But for some reason, after calling morewords, the page refreshes, returning to the original situation.


Solution

  • From Vue's documentation

    Order matters when using modifiers because the relevant code is generated in the same order. Therefore using @click.prevent.self will prevent all clicks while @click.self.prevent will only prevent clicks on the element itself.

    You need to add .prevent to your v-on:click so it becomes v-on:click.self.prevent