`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove the selected item. This issue persists regardless of how many boxes are added or which one is chosen.

App.vue:

<template>
        <the-header title="Remember"></the-header>
        <new-box @add-box="addBox"></new-box>
    <ul>
         <box 
            v-for="box in boxes" 
            :key="box.id"
            :id="box.id"
            :name="box.name"
            :number="box.number"
            @delete="deleteBox(id)">
            </box>
        <big-box>    
            title="Big" info="Additional info"
        </big-box>
    </ul>
</template>

<script>
import TheHeader from './components/layouts/TheHeader.vue';
import Box from './components/boxes/Box.vue';
import BigBox from './components/boxes/BigBox.vue';
import NewBox from './components/boxes/NewBox.vue';

export default {
    components: {
        TheHeader,
        Box,
        BigBox,
        NewBox
    },
    data: () => ({
        boxes: [
            {
            id: "box one",
            name: "name one",
            number: "one"
            }
        ]
    }),
    methods: {
    addBox(name, number) {
            const newBox = {
                id: new Date().toISOString(),
                name: name,
                number: number
            };
            this.boxes.push(newBox);
        },
    findBoxId(boxId) {
        // const identifiedBox = 
        this.boxes.find(
            (box) => box.id === boxId
        );
        // identifiedBox();
    },
        deleteBox(boxId) {
            this.boxes = this.boxes.filter((box) => box.id !== boxId);
        }
    },
};
</script>

<style>
#app input {
  font: inherit;
  padding: 0.15rem;
}
#app label {
  font-weight: bold;
  margin-right: 1rem;
  width: 7rem;
  display: inline-block;
}
#app form div {
  margin: 1rem 0;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Box.vue:

<template>
    <li>
        <base-card>
            <h3>{{ name }}</h3>
            <h5>{{ number }}</h5>
                <!-- <button @click="goRemove">Shoo away the box</button> -->
                <button @click="$emit('deletebox', id)">Shoo away</button>
            </base-card>
    </li>
</template>


<script>
export default {
    props: [
        'id',
        'name',
        'number'
],
emits: ['toggle-favorite', 'deletebox'],
data() {
    return {
        boxItem: {
            id: "one",
            name: "box one",
            number: "one"
            },
        }
    },
    // methods: {
    //     goRemove(boxId) {
    //         this.$emit('deletebox', boxId);
    //     }
    // }
}
</script>

<style scoped>
h3 {
    color: rgb(64, 17, 194);
    text-align: center;
}
li {
    list-style-type: none;
}
</style>

Attempted to use the emit function and work with indexes instead of ids. Added a findBoxId method inspired by the example code and commented out identifiedBox due to errors. Also, tried implementing a separate method in Box.vue but opted to place the emit directly inside the button.

Answer №1

In Box.vue, a child component, you are emitting an event called "deletebox". The parent component is listening for an event named "delete" (@delete).

To fix this, update the event listener in the parent component to @deletebox as shown below:

App.vue

<box 
    v-for="box in boxes" 
    :key="box.id"
    :id="box.id"
    :name="box.name"
    :number="box.number"
    @deletebox="deleteBox($event)">
</box>

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

Condition in Bash script for verifying JSON response

This particular script is designed to notify me whenever there is an error response. Problem: Even when the execution is successful, I am still receiving an email. Bash script: #!/bin/bash DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1&bs ...

How can I reverse the names displayed in ng-repeat when I click?

When utilizing the orderby filter in angularjs, I want to be able to sort the data only when the button is clicked. If the button is not clicked, the sorting order should not be displayed. <tr ng-repeat="tools in toolsfilter | orderBy:orderByField:reve ...

loading a module's dependencies seamlessly with RequireJS

Currently, I am working with Knockout and Require in my project. I have isolated some Knockout handlers into a separate module that I want to utilize. While there is no specific JavaScript code relying on this module, it is referenced in the data-bind attr ...

End the dialogue that relies on information from the Vuetify store

I have a modal dialog that pops up whenever I receive an error message from an API, but I'm facing difficulty in closing it. I am using Vuetify for this purpose. Here is the template code: <v-dialog v-model="isLoginFailed" hide-overlay p ...

Revise the list on the page containing MEANJS components

Utilizing MEAN JS, I am attempting to make edits to the list items on the page, but an error keeps appearing. I have initialized the data using ng-init="find()" for the list and ng-init="findOne()" for individual data. Error: [$resource:badcfg] Error in r ...

Tips on dividing the information in AngularJS

Sample JS code: $scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} .filter('formatData', function () { return function (input) { if (input.indexOf(":") != -1) { var output = input .split ...

Filtering an array of <input> values in JavaScript based on the number of characters they contain

Can someone help me figure out why this JavaScript code isn't working as expected? The intention is to grab the input value from a text box (a string of words separated by spaces), convert it into an array, and then remove any words that are less than ...

Issue with Datepicker validation in Angular 5 and Angular Material

I have implemented the most recent version of Angular and Angular Material. I am facing an issue with a datepicker where the validation requirements are not being met as expected. The documentation states that the required attribute should work by default, ...

Using Laravel Blade Variables in JavaScript Code

Trying to access a variable within blade syntax has posed a challenge for me: success: function(resp) { console.log(resp) var MsgClass = 'alert-danger'; $("#overlay").hide(); ...

Error in Node.js: Unable to access properties of null value within Express

While using Express (with node.js) and MongoDB, I encountered an error when trying to view or update a user profile. The middleware token check worked fine getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (rea ...

knockout.js' $root leads to a page displaying nothing

Using the $root binding context is resulting in a blank page for me. Removing it allows the page to load properly. Causing blank page: <td><input data-bind="value: name" /></td> <td><select data-bind="options: $root.availableMe ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

What could be causing the error message 'Why is 'push' property undefined in React Native?

Within my index.ios.js file, I have the following: renderScene(route, navigator){ return <route.component navigator={navigator} {...route.passProps}/> } as well as render() { return ( <Navigator initialRoute={{name: &a ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

Guide on using JavaScript to automatically scroll a HTML page to the top on any mobile browser

Can JavaScript be utilized to smoothly scroll an HTML page to the top? I am looking to achieve this with a stylish animation that functions correctly on all mobile browsers. jQuery is the library I am using on this particular page. Thank you, ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

`Is it common to use defined variables from `.env` files in Next.js applications?`

Next.js allows us to utilize environment variable files such as .env.development and .env.production for configuring the application. These files can be filled with necessary environment variables like: NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/a ...

Laravel does not have the capability to provide a genuine json response

I am facing an issue with my Laravel controller. The code is straightforward: class MyController extends Controller { public function list() { return response()->json(['a' => 'hello']); } } When I access the ...