When attempting to remove an object from an array in Vue.js, an error may occur stating that the property of the

In my project, I am working with 3 files: App, BlogList, BlogItem. The goal is to enable users to delete a post if they choose to. However, when using splice method, I encountered the following error:

The property or method "removePost" is not defined on the instance but referenced during render. It's essential to make sure that this property is reactive, either in the data option, or by initializing it for class-based components.

Below are snippets of the code (BlogList is included in the App and contains multiple BlogItems):

App:

<template>
  <div id="app">
    <Header />
    <PostList v-bind:posts="posts" />
  </div>
</template>

<script>
import axios from "axios";
import Header from ...
import PostList from ...

export default {
  name: "App",
  components: {
    Header,
    PostList,
  },
data() {
    return {
      posts: []
    };
  }
};
</script>

BlogList:

<template>
<div class="blog-list">
    <div v-for="(post,index) in posts" v-bind:key="post.id">
      <PostItem v-bind:post="[post,index]" />
    </div>
</div>
</template>

<script>
import PostItem from ...

export default {
  name: "PostList",
  components: {
    PostItem
  },
  props: ["posts"],
  methods: {
    removePost: function(index) {
      this.$delete(this.posts, index);
    }
  }
};
</script>

BlogItem:

<template>
  <div class="wrapper">
    <div class="post-text">{{post.data.title}}</div>
      <button class="btn-remove" @click="removePost(index)">Remove</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "PostItem",
  props: ["post"]
};
</script>

I'm still learning Vue and face challenges in passing data between components. I attempted to declare the function in BlogList component where the v-for loop is located, but I struggled to fetch the index of the clicked blog post (which I suspect may be causing issues). I have included only pertinent parts of the code and acknowledged similar questions such as (How to remove an item from an array in Vue.js) but in my case, I prefer to use 3 separate components instead of one.

Answer №1

The function removePost is defined in the BlogList component, but not in the BlogItem component, which results in an error being thrown. Additionally, there is no index available within the scope of the BlogItem component. In this situation, it would be recommended to either emit the event or utilize the slot element.

<template>
  <div class="wrapper">
    <div class="post-text">{{this.post.data.title}}</div>
      <button class="btn-remove" @click="removePost(this.index)">Remove</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "PostItem",
  props: ["post", "index"],
  methods: {
    removePost(index){
     this.$emit('remove-post', index);

    }

  }
};
</script>

Subsequently, in the PostList component, listen for the event within the created() lifecycle hook and call the parent's removePost method:

<template>
<div class="blog-list">
    <div v-for="(post,index) in posts" v-bind:key="post.id">
      <PostItem v-bind:post="[post,index]" />
    </div>
</div>
</template>

<script>
import PostItem from ...

export default {
  name: "PostList",
  components: {
    PostItem
  },
  props: ["posts"],
  created(){
    this.$root.$on('remove-post', function(index){
      this.removePost(index);
    });
  },
  methods: {
    removePost: function(index) {
      this.$delete(this.posts, index);
    }
  }
};
</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

Encountering numerous errors when importing Wallet Connect / Web3 Provider

I encountered some challenges when trying to incorporate the "@walletconnect/web3-provider" JS library into my project. After installing the library along with the Web3 module using the following command: npm install --save web3 @walletconnect/web3-provide ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

Using React Native's stylesheet to apply multiple values in a CSS statement

Here's a scenario to help clarify my question: Imagine I want to add margin to an element in the following way: const myView = () => <View style={styles.viewStyle}></View> const styles = StyleSheet.create({ viewStyle: { margin: ...

Does anyone know of a JavaScript function that works similarly to clientX and clientY but for tooltips when the mouse moves?

When using plain JavaScript to create a function that moves a tooltip on mouse move, the function works the first time with clientX and clientY, but fails to work when repeated. What could be causing this issue with clientX and clientY? Any suggestions on ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

JavaScript code snippet for detecting key presses of 3 specific arrow keys on the document

For this specific action, I must press and hold the left arrow key first, followed by the right arrow key, and then the up arrow key. However, it seems that the up arrow key is not being triggered as expected. It appears that there may be some limitations ...

Making modifications to the database will trigger real-time updates in the web interface. How is it possible to achieve this seamlessly?

Can someone please help me understand how to automatically insert news or new events from a Facebook page as an event in a webpage? I am a programmer and currently, the data is retrieved from the database using AJAX without reloading the page. However, I ...

What is the reason for the unique behavior of v-bind with boolean attributes? More specifically, why is the number 0 considered truthy in

According to the official documentation, <button v-bind:disabled="isButtonDisabled">Button</button> In this example, the disabled attribute will be added if isButtonDisabled is equal to 0, despite the fact that in JavaScript, 0 is co ...

Filtering nested object properties by value using Java Script

I am seeking assistance in filtering nested Objects by property values, with a specific requirement involving values stored in an array. Despite previous similar inquiries, I have yet to find a solution tailored to cases like mine. In reviewing the code s ...

Steps for ensuring a div component appears on top of any other component (like h1 or p)

The outcome of the code below is displayed in this image: https://i.stack.imgur.com/CPDqC.png Is it possible to make the dropdown overlap on top of the 'HELLO's text, hiding the h1 and p tags? I have tried using z-index without success. Making ...

Another option instead of using jQuery to retrieve the active element in the

My goal was to determine when the user is interacting with an INPUT or TEXTAREA element and set a flag variable to true during this engagement. Once the user clicks out of these elements, the flag should be set back to false. To achieve this, I utilized j ...

ReactJS bug: Array rendering problem affected by recent changes

Why does ReactJS remove the first element instead of the middle element when using array.splice to remove an element from an array? This is my code. I am using Redux as well. const reducerNotesAndLogin = (state = initialState, action) => { var tableNo ...

Sending an event to a component that has been rendered in Vue

I'm currently in the process of developing a custom rendered component that will execute a function when clicked on: // Creating a standard Vue component with a render function Vue.component('greeting', { methods: { sayHello(){ ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Combining ApolloProvider and StatsigProvider in ReactJs: A Step-by-Step Guide

Currently in my React (Next.js) application, I am utilizing statsig-react to switch between mastergraphql endpoint URLs. However, I am encountering an issue when trying to connect statsig with Apollo. This is how my app.js file looks like: const apollo = ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

Running a function on a specific route within the same file in Node.js - here's how to do it

I am looking to execute a function on a specific route that is defined within the same file. module.exports.controller = function(app) { app.get('/folders/create', createDirectory); } var createDirectory = function(path, name, permissions, v ...

Conceal the block quotes while substituting with a newline

My HTML page contains numerous comments enclosed in blockquotes. I attempted to implement a feature that allows users to hide all the comments with just one click by using the following JavaScript code: const blockQuotes = document.getElementsByTagName(& ...

Javascript: What is the best way to narrow down search results using multiple values, regardless of the sequence in which they are entered?

React: How can I improve search result filtering to accommodate multiple values (irrespective of word order)? Example: I want to search for the title of a document using variations like "phone repair process," "repair phone process," or "process phone repa ...