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.