Best Practice : Updating child component from grandparent component without mutating props (v-mode, store ?) #12864
Replies: 1 comment 2 replies
-
@mJeromeDiaz Hi ~ You can solve this using
Have a try: Playground In the parent component <template>
<h1>Hello Parent List: {{ pilotes }}</h1>
<ListComponent />
</template>
<script setup>
import ListComponent from './ListComponent.vue'
import { ref, provide } from 'vue'
// Array to store selected pilotes
const pilotes = ref([
'a',
'b',
'c'
])
// Function to update the selected pilotes
const updatePilotes = (pilote) => {
// Update pilotes.value here...
const index = pilotes.value.indexOf(pilote);
if (index === -1) {
pilotes.value.push(pilote)
} else {
pilotes.value.splice(index, 1)
}
}
const createPilote = (pilote) => {
pilotes.value.push(pilote)
}
// Provide pilotes array and the update function to child components
provide('pilotes', pilotes)
provide('updatePilotes', updatePilotes)
provide('createPilote', createPilote)
</script> Then, in the child component <template>
<div>
<h1>Child List: {{ pilotes }}</h1>
<div v-for="(guestItem) in guests" :key="guestItem">
<label>
<input
type="checkbox"
:checked="isSelected(guestItem)"
@change="togglePilote(guestItem)"
/>
{{ guestItem }}
</label>
</div>
<div>
<input v-model="payload" />
<button @click="addPilote()">Create Pilote</button>
</div>
</div>
</template>
<script setup>
// ListComponent.vue
import { ref } from 'vue'
import { inject } from 'vue'
// 👉 Access the pilotes array update function from parent
const pilotes = inject('pilotes')
const updatePilotes = inject('updatePilotes')
const createPilote = inject('createPilote')
const guests = ref(pilotes.value)
const isSelected = (guestItem) => pilotes.value.includes(guestItem)
// Toggle the selection state of a guest
const togglePilote = (guestItem) => {
// Call the update function from the parent
updatePilotes(guestItem)
}
const payload = ref('')
const addPilote = () => {
createPilote(payload.value)
payload.value = ''
}
</script> |
Beta Was this translation helpful? Give feedback.
-
Hey everyone,
I have a grandparent component (guestsComponent) that passes two arrays (guests and pilotes) to a parent component (piloteDialogComponent) which then passes them to a child component (listComponent).
The child component (listComponent) displays a list of guests with checkboxes, allowing users to select or deselect them.
Since pilotes is a prop, I can’t mutate it directly inside listComponent.
I need a way to update the list of selected pilots (pilotes) when a checkbox is checked or unchecked.
What would be the best approach?
Should I use v-model (defineModel), a store (Pinia), or something else?
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions