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
Related videos on Youtube
Author by
abdulmanov.ilmir
Updated on May 25, 2022Comments
-
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:- if you do not output the
productsCount
variable in the HTML, then duplication inconsole.log
does not occur. - if you replace the
mounted
hook withcreated
, then duplication in theconsole.log
also does not occur.
I would be grateful if anyone could explain this behavior.
Vue v2.4.0new 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>
- if you do not output the
-
abdulmanov.ilmir over 6 yearsThanks. And why if you do not output a variable, then the log is not duplicated?
-
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 over 6 years@ Vamsi Krishna In that case, vue is clever :)