I've got a child component that receives a prop from the parent component. I've added an event to update the prop in the parent component when a button is clicked. But the child component does not detect the prop change.
Approximate code:
Parent component:
<template>
<table>
<Student v-for="(student, index) in students"
:key="index"
:student="student"
:attendance="attendance[student.id]"
@attended-clicked="changeAttendance"
></student>
</table>
</template>
<script>
export default {
data() {
return {
students: [
{id: 1, name: 'Pepito'},
{id: 2, name: 'Sue'},
],
attendance: {
1: {attended: true},
2: {attended: false},
}
}
},
methods: {
changeAttendance(studentId) {
this.attendance[studentId].attended = !this.attendance[studentId].attended;
}
}
}
</script>
Child component:
<template>
<tr>
<td>{{ student.name }}</td>
<td><v-btn :color="attendance.attended ? 'green' : 'red'"
@click="$emit('attended-clicked', student.id)"
>Attended</v-btn>
</tr>
</template>
<script>
export default {
props: ['student', 'attendance']
}
</script>
I've tried to keep the code as minimal as possible to give you an idea of what I'm trying to achieve. The expectation is that when the button is clicked, attendance.attended will change.
I can verify that the value is changing when clicked using Vue developer tools (although I have to press the "force refresh" button to see the change). But apparently the child view is not picking up on the change.
Is there something I'm doing wrong here that's breaking reactivity?
I've also tried using Vue.set with some code like this:
methods: {
changeAttendance(studentId) {
let attendance = this.attendance[studentId];
attendance.attended = !attendance.attended;
Vue.set(this.attendance, studentId, attendance);
}
}
No difference.
I appreciate any insight into what I'm doing wrong, thanks!
studentsandattendanceshould be a array i guess