Request: I need help with a situation involving two components, the parent component (Wall.vue) and the child component (PostItem.vue). Each PostItem
includes a delete button. Upon clicking this button, a request is sent to the API to delete the item from the database. Following this deletion, I want to trigger the getPosts
function in the parent component to retrieve all posts again without the recently deleted post.
The Issue: The problem arises within the child component where I am unable to access the this.$parent
Object, specifically as it appears empty and lacks the necessary functions to call the getPosts
function. Interestingly, once I remove the <transition-group>
surrounding both the parent and child components in the parent component, everything functions properly.
Can you identify the underlying issue?
Parent Component (Wall.vue)
template section:
<template>
<div class="Wall view">
<transition-group name="wallstate">
<template v-else-if="messages">
<PostItem
v-for="(message, index) in messages"
:key="index"
:message="message"
:index="index"
class="PostItem"
/>
</template>
<h1 v-else>
Could not load messages. Please try later.
</h1>
</transition-group>
</div>
</template>
script portion:
<script>
import { mapGetters } from 'vuex';
import { postsAPI } from '../services/posts.service.js';
import PostItem from '../components/PostItem.vue';
export default {
components: {
PostItem,
},
data() {
return {
messages: null,
};
},
methods: {
getPosts() {
///////Do stuff
}
}
};
</script>
Child Component (PostItem.vue)
template section:
<template>
<div class="PostItem__message frosted">
<p class="PostItem__messageContent">{{ message.content }}</p>
<p>
by: <strong>{{ message.user.username }}</strong>
</p>
<a
@click="deletePost"
:data-id="message._id"
v-if="message.user._id === user.id"
>
Delete
</a>
</div>
</template>
script portion:
<script>
import { postsAPI } from '../services/posts.service.js';
import { mapGetters } from 'vuex';
export default {
name: 'PostItem',
props: {
message: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
},
computed: {
...mapGetters({
user: 'auth/user',
}),
},
methods: {
deletePost(e) {
const id = e.target.dataset.id;
postsAPI.removeOne(id).then((res) => {
this.$parent.getPosts(); <-------- ISSUE HERE
});
},
},
};
</script>