⊗jsvuPmCmRR 68 of 72 menu

Reactive Component Removal in Vue

Let's learn how to reactively remove child components from the list. Let's make a special button for this in each child component. When this button is clicked, an event will be emitted and the parent component will remove the specified child component by its id.

Let's get started with the implementation. Let the parent component have the following array of objects:

data() { return { users: [ { id: 1, name: 'name1', surn: 'surn1' }, { id: 2, name: 'name2', surn: 'surn2' }, { id: 3, name: 'name3', surn: 'surn3' }, ], } }

Let's write a method for deleting a user by his id in the parent component:

methods: { remove(id) { this.users = this.users.filter((user) => { return user.id !== id; }) } }

Let's create components in a loop, passing them the name, last name, id and a method for deletion as parameters:

<template> <User v-for ="user in users" :id ="user.id" :name ="user.name" :surn ="user.surn" @remove ="remove" :key ="user.id" /> </template>

We will register the incoming data in the props setting and the emitted event in the emits setting:

props: { id: Number, name: String, surn: String, }, emits: ['remove'],

Let's display the user's first and last name in the component view:

<template> {{ name }} {{ surn }} </template>

Now let's make a button that will emit an event for deletion when clicked. The parameter of this event will be id of the component. When the parent component receives the event, it will delete the given user from the array of objects and it will reactively disappear from the list of users.

So, let's implement this button:

<template> {{ name }} {{ surn }} <button @click="$emit('remove', id)"> remove </button> </template>

Output the components Employee in a loop. Make a button in each component to delete it.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline