Deleting an item from an array using Vue.js

1. How can I remove a link using the method from a Vue.js component? Please help me troubleshoot this error: 'method splice is undefined' is showing up in console. Adding a link when inserting a message is not an issue, but removing it seems impossible. Pushing arrays in my single page works fine, but providing a way for the user to remove them is proving challenging.


<div class="list-group">
    <div class="col-lg-4" style="margin-top:3px">
        <input type="text" v-model="link.title" class="form-control" placeholder="title" id="title">
    </div>
    <div class="col-lg-7">
        <input type="text" v-model="link.hyperlink" class="form-control" placeholder="link" id="link">
    </div>
    <div class="col-lg-1">
        <button @click="addLink" type="button" id="add-link-btn" class="btn btn-primary pull-right">+</button>
    </div>
</div>

<div v-for="link in message.links" :key="link.id">
    <div class="row">
        <div class="col-lg-6">
            <p>{{link.title}}</p>
        </div>
        <div class="col-lg-6">
            <a>{{link.hyperlink}}</a>
            <button class="btn btn-xs btn-danger" @click="removeLink(link)">Delete</button>
        </div>
    </div>
</div>

<script>
data() {
    return {
        title: "Add",
        link: {
            id: 1,
            author: "Amedeo",
            title: "",
            hyperlink: ""
        }
    };
},
methods: {
    addMessage() {
        var id = this.messages.length ? this.messages[this.messages.length - 1].id : 0;
        var message = Object.assign({}, this.message);
        message.id = id + 1;
        message.date = new Date();
        this.messages.push(message);

        this.message.title = "";
        this.message.subtitle = "";
        this.message.body = "";
    },
    
    addLink() {
        var messageId = this.messages.length ? this.messages[this.messages.length - 1].id : 1;
        var id = this.message.links.length ? this.message.links[this.message.links.length - 1].id : parseInt(messageId + "0", 10);
        var link = Object.assign({}, this.link);
        link.id = id + 1;
        link.date = new Date();
        this.message.links.push(link);

        this.link.title = "";
        this.link.hyperlink = "";
    },
    
    removeLink(link) {
        this.links.splice(this.links.indexOf(link), 1);
    }
}

Answer №1

Ensure all properties are pre-defined in the data object.

Due to modern JavaScript limitations and the lack of Object.observe support, Vue is unable to detect property additions or deletions.

https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

In your code, if `messages` and `links` are not initially defined in your data object, reactivity will not function properly.

For instance, the following code snippet won't work as expected:

<div id="app">
  Message: {{message}}<br />
  <input type="text" v-on:input="update($event.target.value)" />
</div>
<script>
    new Vue({
    el: '#app',
  data: {
    
  },
  methods: {
    update: function(value) {
        this.message = value;
    }
  }
});
</script>

https://jsfiddle.net/m4q44g7f/

However, the following code snippet works because `message` is defined at the beginning:

<div id="app">
  Message: {{message}}<br />
  <input type="text" v-on:input="update($event.target.value)" />
</div>
<script>
    new Vue({
    el: '#app',
  data: {
    message: ''
  },
  methods: {
    update: function(value) {
        this.message = value;
    }
  }
});
</script>

https://jsfiddle.net/m4q44g7f/1/

Note: There could be other issues in your code, but addressing this one is crucial for proper functionality.

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

Utilizing React, generate buttons on the fly that trigger the display of their respective

Looking for a way to dynamically display 3 buttons, each of which opens a different modal? I'm struggling to figure out how to properly link the buttons to their respective modals. Here's the code I've attempted so far: Button - Modal Code: ...

What is the most efficient way to update all elements within an array in a MongoDB document to a specific value?

Imagine a scenario where I possess the subsequent document: { _id: ObjectId("5234cc89687ea597eabee675"), code: "xyz", tags: [ "school", "book", "bag", "headphone", "appliance" ], qty: [ { size: "S", num: 10, color: "blue" }, ...

A guide to incorporating scroll-triggered animations into Next.js 13

Trying to figure out the best way to incorporate scroll-triggered animations in Next.Js 13. I attempted to utilize a library like AOS, but it requires initialization within a useEffect hook for client-side rendering. If I want AOS functionality available ...

Exploring PHP 7 Arrays: Identifying a specific property within a multi-dimensional array

I'm looking for a way to enhance my PHP IDE (NuSphere PhpEd) to automatically detect the properties of objects within a multidimensional array. Currently, I face an issue where these properties are not displayed when I type a right arrow in my IDE. I ...

The issue of "google not being defined" is commonly encountered in an Angular Project when trying

I am utilizing Google Charts in my Angular project and I am looking to format the values in my chart. I came across this helpful documentation that explains formatters: https://github.com/FERNman/angular-google-charts#formatters Here is a snippet of my co ...

Executing API call utilizing the Request module within a node.js application

In my node.js app, I have a request call that looks like this: request({ url:chanURL, qs:chanProperties}, function(err, response, body) { if(err) { console.log(err); return; } body = JSON.parse(body); (function (body) { Objec ...

The ThreeJS scene may run smoothly at 60 frames per second, but it maxes out my fans and crashes after

Recently, I delved into the world of threeJS and decided to test my skills by using this example: After exporting some terrain from blender and replacing the platform.json file, my scene was running smoothly at 55-60fps. However, as time went on, my compu ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

The issue of calling the store() function on null in Laravel with Nuxt

I'm encountering an issue with saving data in Laravel from my Nuxt Application. I successfully created data using Postman, but for some reason it's not working here. Controller $book = Book::create([ 'name' => $request ...

What is the best way to create an associative array using jQuery and then send it through AJAX to be parsed by PHP?

Is there a way to create an associative array in jQuery and send it via ajax to a php page for processing? Here is an example of what I am trying to achieve... // jQuery if($something == true) { data[alt] = $(this).attr('alt'); data[sr ...

Looking for a way to automatically load an aspx page when the browser is closing

Hey there, I'm struggling to load an aspx page when the browser is closed. I thought I had the code right, but it's not working. Can someone please lend a hand? Thanks! var clicked = false; function CheckBrowser() { ...

There was an error while trying to read the properties of undefined (specifically the state). Make sure to include this.state.a

I am struggling with an error that I have never encountered before. Despite having experience working with functional components, I am new to class components. I used create react app to install the application, but it seems like I might be missing a req ...

Discovering how to efficiently track and respond to changes in MobX state within a React

Within my react native project, I have observed that upon clicking a button, the state of my mobx app undergoes an update. To address this issue, I aim to employ a react lifecycle method that can monitor and automatically reflect this modification. For th ...

Showing arbitrary text on Vue.js template

In my Vue.js application, I have a Loader component that randomly displays one of several messages. Here is how I implemented it: Vue.component('Loader', { data() { const textEntries = [ 'Just a moment', ...

How should one go about creating and revoking a blob in React's useEffect function?

Consider this scenario: import { useEffect, useState, type ReactElement } from 'react'; async function getImage(): Promise<Blob> { // Some random async code const res = await fetch('https://picsum.photos/200'); const blob = ...

Fixing the "Module not found" error in an Angular library using npm link

I'm currently working on creating an Angular wrapper for a Javascript library, but I've encountered a "Module not found" error. The Javascript library is still in development and has not been published to NPM yet. To work around this issue, I hav ...

What is the best way to concatenate multiple string arrays in C and return the resulting array of strings?

Searching for a way to extract a specific array string from a deck containing 52 playing cards. The 'deck[]' array is made up of combined string arrays representing suits and values. Can you provide guidance on how to achieve this, along with the ...

Establishing Connections to Multiple MySQL Databases Using Node.js

I'm struggling to incorporate a dropdown menu that displays all the databases from a set host. The idea is to allow users to choose a database from the drop-down and generate a report. However, I can't figure out how to connect to the host and po ...

Inserting a Div Element into a List Using a User-Entered Variable (jQuery)

For a school project, I am currently working on a task involving multiple "Add Task" buttons with prompts that appear when clicked. The goal is to have the entered item added to the bottom of the corresponding list. I have experimented with options like a ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...