You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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-for Syntax: The line v-for="(item, index) in boxCount" tells Weex to render the .box element exactly boxCount times. The index variable gives you the current iteration number (starting at 0) if you need to add dynamic content or styling per box.
  • :key Binding: 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 boxCount value in the data section 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:22:04