Vue.js实现文章评论和回复评论功能

2020-06-16 05:53:13易采站长站整理

{
responder: "傲娇的", //评论者
reviewers: "有毒的黄同学", //被评论者
time: "2016-09-05",
content: "你说得对"
}
}
]

再来看commemt-content组件


Vue.component('commemt-content',{
template:'
<div class="commentBox">
<h3>评论</h3>
<p v-if="comment.length==0">暂无评论,我来发表第一篇评论!</p>
<div v-else>
<div class="comment" v-for="(item,index) in comment" v-bind:index="index" >
<b>{{item.name}}<span>{{item.time}}</span></b>
<p @click="changeCommenter(item.name,index)">{{item.content}}</p>
<div v-if="item.reply.length > 0">
<div class="reply" v-for="reply in item.reply">
<b>{{reply.responder}}  回复  {{reply.reviewers}}<span>{{reply.time}}</span></b>
<p @click="changeCommenter(reply.responder,index)"">{{reply.content}}</p>
</div>
</div>
</div>
</div>
</div>',
props: ['comment'],
methods: {
changeCommenter: function(name,index) {
this.$emit("change",name,index);
}
}
});

如果没有内容,则显示 “暂无评论,我来发表第一篇评论!”。如果有内容就开始遍历。因为点击评论要知道第几条,所以每条评论要绑一个v-bind:index=”index”

到了二次评论那块,还是遍历reply数组,绑定该绑定的。因为就算点击内容,也是加到那条一级评论的最下面,所以两个点击事件我都是绑定了同一个事件。只是传进去的名字不一样而已,后面那个index都是一级评论的index。

changeCommenter事件触发了change,父组件监听,执行相应行为。

父组件


var comment = new Vue({
el: "#comment",
data: {
commenter: "session", //评论人,这里会从session拿
type: 0, //0为评论作者1为评论别人的评论
oldComment: null, //久评论者的名字
chosedIndex: -1, //被选中的评论的index
article: {
title: "当归泡水喝的九大功效",
time: "2016-07-12",
read:50,
content: ""
},
comment: [] //评论内容
},
methods: {
//添加评论
addComment: function(data) {
if(this.type == 0) {
this.comment.push({
name: 'session',
time: getTime(),
content: data,
reply: [] });
//服务器端
}else if(this.type == 1){
this.comment[this.chosedIndex].reply.push({
responder: 'session',
reviewers:this.comment[this.chosedIndex].name,
time: getTime(),
content: data
});
this.type = 0;
}
},