【发布时间】:2018-09-28 09:02:36
【问题描述】:
我是 Vue 的新手,我正在构建这种可以在其中添加嵌套 cmets 的论坛。这里有两个组件。 PostForum 和评论。 PostForum 包含一个输入框和父评论。在每条评论中,我递归地添加了子 cmets。
当我添加 cmets 时,它工作正常。但是在删除时,它会发送 ajax req 但没有重新渲染。 所以这就是我设计它的方式。删除评论时,我会发出一个全局事件,并在 PostForum 组件中监听该事件并从其数据中删除该评论。那么这不应该相应地重新渲染所有的 cmets 吗?谁能告诉我我在这里做错了什么?
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>
【问题讨论】:
-
首先您需要将
name添加到comment组件。如果没问题,然后重试?export default { name: "Comment", ... } -
当然我加了名字,只是上面没提,因为很明显。对吗?
标签: javascript vue.js