Vue报错:无法在有状态组件根元素上使用v-for,求助解决
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-boxelements don't exist yet (thev-forhasn't run to render them). - Even if they did,
v-forwould create multiple elements with the sameid="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
- Mount to a static element:
#location-sectionexists in the DOM when Vue initializes, so Vue can attach itself correctly and render thev-forloop without issues. - Add a
:keytov-for: Vue requires a unique key for list items to track changes efficiently—using the loop index works perfectly for simple lists like this. - 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

