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

Vue报错:无法在有状态组件根元素上使用v-for,求助解决

Fixing Your Vue.js Mounting & v-for Issue

Hey there! I see exactly what's tripping you up here—let's break it down and fix it step by step.

The Core Problem

Your Vue instance is trying to mount to #location-box, but that element is being generated inside a v-for loop. Here's why that's a problem:

  • When Vue initializes, the #location-box elements don't exist yet (the v-for hasn't run to render them).
  • Even if they did, v-for would create multiple elements with the same id="location-box"—duplicate IDs are invalid HTML and will cause weird behavior with DOM selection.

The Fix

We need to adjust your structure so Vue mounts to a static parent container, and fix the duplicate ID issue.

Updated Vue Instance

We'll keep your data intact, but mount to a static top-level container that exists in the DOM from the start:

const app = new Vue({
  el: '#location-section',
  data: {
    locations: [
      { name: "Europe", desc: "Loren ipsum" },
      { name: "America", desc: "Loren ipsum" }
    ],
  }
})

Updated HTML

Move the v-for to a container inside the mounted element, replace the duplicate ID with a class, and add a required unique key for the loop:

<div id="location-section">
  <div class="main-container">
    <div class="location-grid-container">
      <div id="info-box" class="outline"> </div>
      <div>
        <!-- Use a class instead of duplicate ID, add unique key for v-for -->
        <div v-for="(location, index) in locations" :key="index" class="location-box outline">
          <h1>{{location.name}}</h1>
        </div>
      </div>
    </div>
  </div>
</div>

Key Changes Explained

  1. Mount to a static element: #location-section exists in the DOM when Vue initializes, so Vue can attach itself correctly and render the v-for loop without issues.
  2. Add a :key to v-for: Vue requires a unique key for list items to track changes efficiently—using the loop index works perfectly for simple lists like this.
  3. Remove duplicate ID: Swapped id="location-box" for a class (.location-box) to avoid invalid HTML. If you need unique IDs for each item later, you could use :id="location-box-${index}" instead.

That should resolve your mounting error and get your locations rendering properly!

内容的提问来源于stack exchange,提问作者Donnie Berry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:54:56