在实际的开发过程中可能会遇到要展示树状评论的需求,这里我们需要运用到递归。
通过组件的递归来实现展示树状评论的效果
// 子组件
<template>
<div>
<div v-for="(item, index) in commentParams" :key="index">
<div @click="commentID(item)">
<span>{{ item.comment }}</span>
</div>
<input v-if="item.child" v-model="comment" />
<button style="margin: 10px 0 10px 10px" @click="reply(item)">
回复
</button>
<div>
// 递归调用组件本身
<Comment :commentParams="item.children"></Comment>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'comment',
props: {
commentParams: {
type: Array,
require: true,
},
},
data() {
return {
isShow: null,
comment: '',
};
},
created() {},
watch: {},
methods: {},
};
</script>
// 父组件
<template>
<div class="about">
<span>父组件</span>
<input v-model="comment" />
<button style="margin: 10px 0 10px 10px">第一级评论</button>
<div style="margin-right: 10px; color: red">
// 使用子组件
<Comment :commentParams="treeData"></Comment>
</div>
</div>
</template>
<script>
import Comment from '@/components/comment.vue';
export default {
components: { Comment, Nav },
data() {
return {
comment: '',
// 模拟树状评论集
treeData: [
{
id: '0100',
comment: '第二级级评论',
children: [
{
id: '0110',
comment: '第二级回复',
},
{
id: '0120',
comment: '第二级回复',
},
{
id: '0130',
comment: '第二级回复',
},
],
},
{
id: '0200',
comment: '第三级级评论',
},
{
id: '0300',
comment: '第四级级评论',
},
{
id: '0400',
comment: '第五级级评论',
},
{
id: '0500',
comment: '第六级评论',
children: [
{
id: '0510',
comment: '第六级回复',
},
{
id: '0520',
comment: '第六级回复',
children: [
{
id: '0521',
comment: '第六级回复的回复',
},
{
id: '0522',
comment: '第六级回复的回复',
children: [
{
id: '05221',
comment:
'第六级回复的回复的回复',
children: [
{
id: '052211',
comment:
'第六级回复的回复的回复的回复',
},
{
id: '052212',
comment:
'第六级回复的回复的回复的回复',
},
],
},
{
id: '05222',
comment:
'第六级回复的回复的回复',
},
],
},
],
},
],
},
],
};
},
created() {},
methods: {},
};
</script>