I've been trying to implement two-way binding using v-model in Vue.js based on this article. The idea is to pass values from a parent component to a child component with automatic event emission when the value changes in the child component. However, I'm encountering issues with my implementation.
Here's a snippet of my code:
<template>
<!-- This is ParentComponent.vue -->
<ChildComponent v-model:documents="user.documents" />
</template>
<script lang="ts">
// This is ParentComponent.vue
import { Vue, Options } from 'vue-class-component';
import UserClass from '@/some/place/UserClass';
import ChildComponent from '@/components/ChildComponent.vue';
@Options({
components: {
ChildComponent,
}
})
export default class ParentComponent extends Vue {
// Local state.
user: UserClass = new UserClass();
}
</script>
<template>
<!-- This is ChildComponent.vue -->
<section v-for="document in documents" :key="document.id">
{{ document.name }}
<button @click="remove(document.id)">Delete document</button>
</section>
</template>
<script lang="ts">
// This is ChildComponent.vue
import { Vue, Options } from 'vue-class-component';
import IDocument from '@/interfaces/IDocument';
@Options({
props: ['documents'],
emits: ['update:documents'],
})
export default class ChildComponent extends Vue {
// Types.
documents!: IDocument[];
// Methods.
remove(documentId: string): void {
this.documents = this.documents.filter((document) => document.id !== documentId);
}
}
</script>
My expectation was that clicking a button in the child component would trigger the "remove()" method and emit an update:documents event instead of directly updating this.documents. This emitted event should then be caught by the parent component to update its own local state.
However, I'm receiving the following warning:
Attempting to mutate prop "documents". Props are readonly.
And also an error:
Uncaught TypeError: proxy set handler returned false for property '"documents"'
Could you please help me identify where I went wrong? Thank you in advance.