In Vue 3, the v-model feature is utilized as parameter passing instead of using :prop and @emit

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.

Answer №1

It seems I overlooked a key aspect of how v-model operates. Initially, I assumed that by passing a value using v-model in this manner:

<ChildComponent v-model:documents="user.documents" />

an update:documents event would be emitted automatically whenever the documents prop's value changed within the ChildComponent. However, it appears that you still need to manually emit this event as shown below:

<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 {
      // The user.documents in the ParentComponent will be replaced with the filtered array generated here in the child.
      this.$emit('update:documents',  this.documents.filter((document) => document.id !== documentId));
    }
  }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Issues with executing code within the react package for Yahoo Finance 2

I am currently in the process of developing a React application using Vite. The purpose of my app is to retrieve stock-related information from Yahoo using the yahoo-finance2 package. Interestingly, when I run the code as a standalone JavaScript file, eve ...

Presentation of information with loading and error scenarios

How can we effectively display data in an Angular view, considering loading state and error handling? Imagine we are fetching a set of documents from our backend and need to present them in an Angular view. We want to address three possible scenarios by p ...

Testing Angular: How to Unit-test HttpErrorResponse with custom headers using HttpClientTestingModule

In the code snippet below, I am attempting to find a custom header on error: login(credentials: Credentials): Observable<any> { return this.http.post(loginUrl, credentials) .pipe( catchError((httpErrorResponse: HttpErrorRespo ...

Tips for executing Firebase transactions involving read operations subsequent to write operations

Is there a method to incorporate read operations following write operations in nodejs for cloud and background functions? According to the information provided in the documentation, only server client libraries allow transactions with read operations afte ...

Having trouble with TypeScript error in React with Material-UI when trying to set up tabs?

I have developed my own custom accordion component hook, but I am encountering the following error export default const Tabs: OverridableComponent<TabsTypeMap<{}, ExtendButtonBase<ButtonBaseTypeMap<{}, "button">>>> Check ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

Arrange an array within an Angular component

I'm in the process of organizing my list-component made with Angular Material. <div style="width:30%;"> <mat-nav-list matSort (matSortChange)="sortData($event)"> <th mat-sort-header="stuff.name">Name</th> ...

How to implement SVG in React with the image source as a parameter?

I've been working on a React component in NextJS that displays an image inside a hexagon. The issue I'm facing is that when I try to use multiple instances of this component with different images in the HexagonWall, all hexagons end up displaying ...

What is causing the issue of URL parameters becoming undefined when performing service injection in the app component?

When working with a service that reads parameters from the URL, everything seems to be functioning properly until attempting to inject the service into the constructor of the app.component.ts file or trying to call a service method from the app.component.t ...

Jest: A guide on mocking esModule methods

In my code, I have a function that utilizes the library jszip to zip folders and files: // app.ts const runJszip = async (): Promise<void> => { const zip = new Jszip(); zip.folder('folder')?.file('file.txt', 'just som ...

Using InjectionToken results in the generation of the error message "Encountered an issue while resolving symbol values

Recently, I encountered an issue while building my Ionic 3 app using ionic cordova build ios --prod. Everything was functioning perfectly until a package update caused some complications, preventing me from successfully building the app. I suspect that t ...

Preserve the checkbox state upon refreshing the page

I am facing an issue with keeping the checkbox state saved after a page reload. Currently, I have stored my unchecked checkboxes in localStorage, but I am unsure about what steps to take next. In simple terms, I want the checkbox to remain unchecked when I ...

What is preventing me from consistently accessing the Type Definition while my cursor is on a JavaScript/TypeScript parameter name in VS Code, and what are some strategies I can use to overcome this issue?

Imagine I have the following code snippet in my VS Code: type T1 = { x: number }; type T2 = { x: number } & { y: string }; function foo(arg1: T1, arg2: T2) {} If I place my cursor on arg1 and go to the type definition (either through the menu or a sh ...

Nextjs introduces an innovative "OnThisDay" functionality, leveraging getServerSideProps and Date.now() to provide real-time information

I am currently working on adding an "OnThisDay" feature in my Nextjs project, inspired by Wikipedia's style of displaying events that happened on a specific date. To achieve this, I have implemented a function structured like the following code snippe ...

The Angular program is receiving significant data from the backend, causing the numbers to be presented in a disorganized manner within an

My Angular 7 application includes a service that fetches data from a WebApi utilizing EntityFramework to retrieve information. The issue arises when numeric fields with more than 18 digits are incorrectly displayed (e.g., the number 23434343434345353453,3 ...

I am encountering an issue where my TSX import is being declared but not read when I attempt to pass it to the Jest render method. Can anyone explain

My Jest test file includes a simple import of a TSX component in my nextjs 13 project. However, when I try to use the component as a TSX tag, an error occurs: "'Properties' refers to a value, but is being used as a type here. Did you mean ...

Retrieving source in Angular from an async function output within a specified time limit

I have a quick query :). I'm attempting to retrieve the image src from an async function, but so far, I haven't had much success. This is what I have: <img [src]="getProductImage(articleNumber)"/> and in my TypeScript file: publi ...

Ways to parse the data from a response received from an Axios POST request

After sending the same POST request using a cURL command, the response I receive is: {"allowed":[],"error":null} However, when I incorporate the POST request in my code and print it using either console.log("response: ", resp ...