Vue.js中能否在el选项中指定多个DOM元素ID?
el option of a Vue instance? Short answer: No, you can’t pass multiple selectors like '#app, #app1' to the el option of a single Vue instance.
Why is that?
Vue is built to mount one instance to exactly one root DOM element. The el option only accepts two types of values:
- A single CSS selector string (pointing to one unique element), or
- A direct DOM element object.
If you try to pass multiple selectors, Vue will either mount only to the first matching element it finds, or fail silently if no valid element is detected—neither outcome will let you target both #app and #app1 with one instance.
Solutions to target multiple elements
If you need to manage multiple DOM elements with Vue, here are your practical options:
1. Mount to a shared parent container
Wrap both #app and #app1 inside a single parent element, then mount your Vue instance to that parent. This lets both inner elements fall under the instance’s scope:
<div id="root-container"> <div id="app"></div> <div id="app1"></div> </div>
var app = new Vue({ el: '#root-container', data: {} })
2. Create separate Vue instances
If the two elements need independent state or logic, create a dedicated instance for each:
// Mount to #app var app = new Vue({ el: '#app', data: {} }) // Mount to #app1 var app1 = new Vue({ el: '#app1', data: {} })
This keeps each instance’s scope isolated, which is often the cleanest approach when the elements don’t share much functionality.
3. Use Vue Components (for reusable logic)
If you’re repeating similar behavior across multiple elements, wrap that logic in a component and reuse it wherever needed:
// Define a reusable component Vue.component('my-shared-component', { template: '<div>{{ greeting }}</div>', data() { return { greeting: 'Hello from the component!' } } }) // Mount a root instance to a parent container var app = new Vue({ el: '#root-container' })
Then use it in your HTML:
<div id="root-container"> <my-shared-component id="app"></my-shared-component> <my-shared-component id="app1"></my-shared-component> </div>
Fixing your original code
Your current code won’t work as intended—here’s a corrected version if you want separate instances:
var app = new Vue({ el: '#app', data: { } }) var app1 = new Vue({ el: '#app1', data: { } })
内容的提问来源于stack exchange,提问作者portes port

