如何在Weex模板中实现for循环以重复渲染n次盒子?
Solution: Use Weex's
v-for Directive for Loop Rendering Nice question! In Weex (which shares a lot of Vue's template syntax), you can use the v-for directive to replicate that for loop logic, eliminating the need to manually copy-paste the same .box component repeatedly. Here's how to refactor your code cleanly:
<template> <div> <!-- Render the box component n times using v-for --> <div class="box" v-for="(item, index) in boxCount" :key="index"></div> </div> </template> <script> export default { data() { return { boxCount: 7 // Adjust this number to set how many boxes you need } } } </script> <style scoped> .box { border-width: 2px; border-style: solid; border-color: #BBB; width: 250px; height: 250px; margin-top: 250px; margin-left: 250px; background-color: #EEE; } </style>
Key Details to Note:
v-forSyntax: The linev-for="(item, index) in boxCount"tells Weex to render the.boxelement exactlyboxCounttimes. Theindexvariable gives you the current iteration number (starting at 0) if you need to add dynamic content or styling per box.:keyBinding: Adding:key="index"is a best practice—it helps Weex efficiently update the DOM by tracking each element's unique identity, which improves rendering performance.- Dynamic Control: Now you only need to modify the
boxCountvalue in thedatasection to change how many boxes are rendered. No more editing the template manually!
If you later need to pass unique data to each box (like custom colors or content), you can also loop over an array of objects instead of a number. For example:
data() { return { boxes: [ { id: 1, bgColor: '#EEE' }, { id: 2, bgColor: '#DDD' }, // Add more box data as needed ] } }
Then update the template to use this array:
<div class="box" v-for="box in boxes" :key="box.id" :style="{ backgroundColor: box.bgColor }"></div>
内容的提问来源于stack exchange,提问作者Anant Raj
相关产品推荐
相关产品推荐

