Context
In my Vue 3 application, there is a HomeView component that contains the following template structure:
<InputsComponent></InputsComponent>
<CheckboxesComponent></CheckboxesComponent>
<Toolbar></Toolbar>
The InputsComponent displays text inputs, while the CheckboxesComponent displays checkboxes.
The Toolbar component includes buttons, including a "reset" button.
This question focuses on how to facilitate communication between sibling components.
Objective
When a user fills in inputs or selects checkboxes, pressing the reset button in the Toolbar should reset both the InputsComponent and CheckboxesComponent, allowing users to fill them again and reset as needed. The logic of resetting within each component is not important; what matters is coordinating communication among the three components.
Prior Knowledge
I am avoiding using EventBus in Vue 3 as it is discouraged.
Attempted Solution
I attempted utilizing the parent component as a bridge for communication:
Toolbar.vue
<button @click="$emit('reset')"> Reset </button>
HomeView.vue
<script setup>
const state = reactive({
resetRequested: false
})
function requestReset() {
state.resetRequested = true;
}
</script>
<template>
<main>
<InputsComponent :reset-requested="state.resetRequested"></InputsComponent>
<CheckboxesComponent :reset-requested="state.resetRequested"></CheckboxesComponent>
<Toolbar @reset="requestReset()"></Toolbar>
</main>
</template>
InputsComponent.vue
<script setup>
const props = defineProps({
resetRequested: boolean,
})
watch(
() => props.resetRequested,
(resetRequested) => {
if (resetRequested == true)
//logic to reset the inputs
}
)
</script>
<template>
<main>
<input type="text" /> //and other input elements
</main>
</template>
CheckboxesComponent functions similarly but with checkboxes.
This approach works initially, but I face issues when trying to hit the reset button multiple times since the prop remains set to true
. I also tried having InputsComponent emit an event to the parent to change the prop value to false, but this caused an overall breakdown in behavior.
Challenge
Is there a more efficient way to handle this communication rather than constant back-and-forth interactions between children and their parent? This complexity seems unnecessary.
My current process involves:
- Toolbar sending an event to HomeView
- HomeView updating a prop in CheckboxesComponent and InputsComponent
- CheckboxesComponent and InputsComponent responding to the prop update and performing their actions, then sending an event back to HomeView
- HomeView resetting the props in CheckboxesComponent and InputsComponent to start the cycle anew
This method feels convoluted and cumbersome.
Additionally, ensuring that both Components reset simultaneously or giving the parent a separate state variable for each child adds further complications.
What am I overlooking? Is there a better approach I could take instead of persisting with this intricate process?