I've just started working with Vue and I'm currently developing a forum-style application that allows nested comments. Within this structure, there are two main components: PostForum and Comment. The PostForum component consists of an input box for adding comments and parent Comments. Each individual comment can contain child comments added recursively.
While adding comments works perfectly fine, I've encountered an issue when trying to delete them. Although the AJAX request is sent upon deletion, there seems to be no re-rendering happening on the page. This is how I planned it: when a comment is deleted, I emit a global event that is then listened to in the PostForum component. Upon receiving this event, the corresponding comment is removed from the data. Shouldn't this trigger a re-render of all the comments accordingly? Could someone point out where I might be going wrong?
PostForum.vue
<template>
<!-- comment box here -->
<comment
v-for="(comment, index) in comments"
v-if="!comment.parent_id"
:reply="true"
:initialChildren="getChildren(comment.id)"
:key="index"
:comment="comment">
</comment>
</template>
<script>
export default {
data () {
return {
comments: [], // all comments
comment: { // new comment [at comment box]
body: '',
parent_id: 0,
},
}
},
methods: {
deleteComment (node) {
axios.delete(`/comments/${node.id}`)
.then(res => {
this.comments.splice(node.key, 1)
})
.catch(err => {
console.log(err)
})
},
getChildren: function (parent_id) {
return this.comments.filter(child => parent_id == child.parent_id)
},
},
mounted: function () {
window.Event.$on('comment-deleted', (node) => this.deleteComment(node))
}
}
</script>
Comment.vue
<template>
<button @click="deleteComment">X</button>
<!-- comment body goes here -->
<comment v-for="(child, i) in children" :key="i" :reply="false" :comment="child"></comment>
<!-- reply form here -->
</template>
<script>
export default {
props: ['initialChildren']
data: function () {
return {
newComment: {
body: '',
parent_id: this.comment.id,
},
children: this.initialChildren,
}
},
methods: {
deleteComment () {
window.Event.$emit('comment-deleted', {key: this.$vnode.key, id: this.comment.id})
},
}
}
</script>