Independent Instances
Part of the Fundamentals section of Coddy's Vue journey. Lesson 32 of 55.
Rendering a component twice creates two instances. A ref declared inside that child's script setup is created separately for each instance, so clicking one counter does not change the other.
// Inside VisitCounter.vue:
const visits = ref(0);
// <p>{{ visits }}</p><button @click="visits++">Visit</button>
// Parent: <VisitCounter /><VisitCounter />Reuse shares the component definition, not all of its state. Avoid fixed ids inside a repeated child because ids must be unique on a page. Classes or unique parent wrappers let you identify repeated UI without colliding ids.
Challenge
MediumCreate a SignupCounter.vue component with a local count ref starting at zero, a paragraph class="count", and a button that adds one. Render 2 instances inside wrappers counter-1 through counter-2 in main#result. Each instance must keep an independent count.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
7Reusable Components
Importing ComponentsIndependent InstancesPassing PropsProp Types and DefaultsRecap: Component Cards2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks