Episode 14 of 44
Multiple Vue Instances
Create and manage multiple Vue instances on a single page — understand scope, communicate between instances, and know when to use components instead.
Multiple Vue Instances
You can have more than one Vue instance on a single page. Each instance controls its own section of the DOM.
Two Independent Instances
<div id="app-one">
<h2>{{ title }}</h2>
</div>
<div id="app-two">
<h2>{{ title }}</h2>
<button @click="changeTitle">Change App One Title</button>
</div>
<script>
var one = new Vue({
el: '#app-one',
data: { title: 'App One' }
});
var two = new Vue({
el: '#app-two',
data: { title: 'App Two' },
methods: {
changeTitle() {
one.title = 'Title Changed by App Two!';
}
}
});
</script>
Cross-Instance Communication
You can access one instance from another by storing it in a variable. two modifies one.title directly. While this works, it tightly couples the instances — components (next episode) are a better approach.
When to Use Multiple Instances
| Scenario | Use |
|---|---|
| Adding Vue widgets to an existing non-Vue page | Multiple instances |
| Building a full single-page application | Single instance with components |
| Two completely independent parts of a page | Multiple instances |
Key Takeaways
- Multiple Vue instances can exist on the same page, each controlling a different DOM element
- Instances can communicate by referencing each other through variables
- For most apps, components (next episode) are the better way to organize your code