数据结构
有不知道多少和多深的child
父组件
newstree组件是一个循环递归的子组件
这里有一个itemChild是数据结构需要递归的数据
deep这个是递归的深度
ref是父组件触发子组件所用
我这里可能有不同的层级的子组件所以不是单一的所以是个动态的
<div class="replay_child">
<newstree
:itemChild="item.child"
v-if="item.child != false"
:deep="deep"
:ref="`child${item.id}`"
:key="'father' + item.id"
@getcommentid="getcommentid"
></newstree>
</div>
子组件
这里的关键还是子组件循环调用自己
值得注意的地方就是需要加 name: “comment-tree”,不然无法区分是调用的自己
关键的代码:
<comment-tree
v-if="itemChild"
:itemChild="item.child"
:deep="deep + 1"
:key="'son' + item.id"
@getcommentid="reply"
:showreply="flag"
>
</comment-tree>
<template>
<div class="comment-wrap">
<div
v-for="(item, index) in child"
:key="index"
:style="{
'margin-left': deep >= 74 ? '0px' : '0.1rem',
'word-wrap': 'break-word',
}"
class="replay"
v-if="flag || showreply"
>
<div
:style="{
width: 9 - deep * 0.1 + 'rem',
'word-wrap': 'break-word',
}"
>
{{ item.user_name }} : {{ item.c_body }}
<span @click="reply(item)" class="reply_span cu">回复</span>
</div>
<comment-tree
v-if="itemChild"
:itemChild="item.child"
:deep="deep + 1"
:key="'son' + item.id"
@getcommentid="reply"
:showreply="flag"
>
</comment-tree>
</div>
</div>
</template>
<script>
export default {
data() {
return {
child: "",
flag: false,
};
},
name: "comment-tree",
props: ["itemChild", "deep", "showreply"],
methods: {
reply(item) {
this.$emit("getcommentid", item);
},
reply1(item) {
this.$emit("getcommentid", item);
},
changeshow() {
this.flag = !this.flag;
},
},
computed: {
itemChildfn() {
if (this.itemChild != false) {
return this.itemChild;
}
},
},
watch: {
itemChildfn(newValue) {
this.child = newValue;
},
},
created() {
this.child = this.itemChild;
this.flag = this.showreply;
},
};
</script>