Home » vue » Vue Method is executing multiple times

Vue Method is executing multiple times

Posted by: admin November 26, 2021 Leave a comment

Questions:

I simply have a method to display the name. Inside that method is a counter incrementing, so that I know how many times the method was called. But upon page load, the method was executed multiple times, 102 times to be exact.

<template>
      <div class="row g-2">
        <div class="col-sm-4">
          <div>Enter your name</div>
          <input type="text" v-model="name" /> <br />
          Your name is : {{ outputName() }}
          <div class="border border-danger">Counter : {{ counter }}</div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          name: "",
          counter: 0,
        };
      },
      methods: {
        outputName() {
          this.counter = this.counter + 1;
    
          return this.name;
        },
      },
    };
    </script> 

Output

enter image description here

Answers:

This is doing an infinite loop because you’re calling a method inside template which updates a property that’s also in the template which does multiple rendering and in each rendering it update the property, just print the name inside the template, then use an event to update the counter like using a button :

<template>
      <div class="row g-2">
        <div class="col-sm-4">
          <div>Enter your name</div>
          <input type="text" v-model="name" /> <br />
          Your name is : {{ name }}
          <div class="border border-danger" @click="counter++">Counter : {{ counter }}</div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          name: "",
          counter: 0,
        };
      },
      methods: {
        outputName() {
          this.counter = this.counter + 1;
    
        },
      },

    };
    </script>