Vue v-for output to console.log

11,788

mounted() hook is called after the DOM has been mounted, which means the cell() method is already called while mounting the DOM.

In your mounted hook you are updating the data property which causes a rerender inturn calling the cell() method again. That's the reason you see your log appearing 2 times

Share:
11,788

Related videos on Youtube

abdulmanov.ilmir
Author by

abdulmanov.ilmir

Updated on May 25, 2022

Comments

  • abdulmanov.ilmir
    abdulmanov.ilmir almost 2 years

    The following example prints the list in HTML. The output in HTML is normal. But the output of the same list in console.log is duplicated. Why? I could not find an answer, but I noticed the following:

    1. if you do not output the productsCount variable in the HTML, then duplication in console.log does not occur.
    2. if you replace the mounted hook with created, then duplication in the console.log also does not occur.

    I would be grateful if anyone could explain this behavior.
    Vue v2.4.0

    new Vue({
      data: {
        products: [1, 2, 3],
        productsCount: 0
      },
      methods: {
        cell(product) {
          console.log(product);
          return product;
        }
      },
      mounted() {
        this.productsCount = this.products.length;
      }
    }).$mount('#products');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>
    <div id="products">
      <h6>productsCount: {{productsCount}}</h6>
      <ul>
        <li v-for="(product, index) in products">
          <span v-html="cell(product)"></span>
        </li>
      </ul>
    </div>

  • abdulmanov.ilmir
    abdulmanov.ilmir over 6 years
    Thanks. And why if you do not output a variable, then the log is not duplicated?
  • Vamsi Krishna
    Vamsi Krishna over 6 years
    @abdulmanov.ilmir even though if you do not output a variable in the html, If the data object updates it causes a rerender.
  • abdulmanov.ilmir
    abdulmanov.ilmir over 6 years
    @ Vamsi Krishna In that case, vue is clever :)