javascript Vue v-for 输出到 console.log
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47196373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue v-for output to console.log
提问by abdulmanov.ilmir
The following example prints the list in HTML. The output in HTML is normal. But the output of the same list in console.logis duplicated. Why? I could not find an answer, but I noticed the following:
以下示例以 HTML 格式打印列表。HTML 中的输出是正常的。但是相同列表中的输出console.log是重复的。为什么?我找不到答案,但我注意到以下几点:
- if you do not output the
productsCountvariable in the HTML, then duplication inconsole.logdoes not occur. - if you replace the
mountedhook withcreated, then duplication in theconsole.logalso does not occur.
- 如果不输出
productsCountHTML 中的变量,则console.log不会发生重复输入。 - 如果用 替换
mounted钩子created,则console.log也不会发生重复。
I would be grateful if anyone could explain this behavior.
Vue v2.4.0
如果有人能解释这种行为,我将不胜感激。
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>
采纳答案by Vamsi Krishna
mounted()hook is called after the DOM has been mounted, which means the cell()method is already called while mounting the DOM.
mounted()hook 在 DOM 挂载后被调用,这意味着cell()在挂载 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
在您挂载的钩子中,您正在更新 data 属性,这会导致cell()重新渲染再次调用该方法。这就是您看到日志出现 2 次的原因

