递归获取评论并递归展示(SteemJS) / 网络研习社#49

in #steemjiang5 years ago

reply.jpg

今天查了下社区的文章,倒也是把递归获取评论的事给解决了,社会的技术分享还是挺不错的!这是地址,有兴趣的小伙伴也可以去看看:
参考1 参考2

经过一番改进,递归函数挺完美了:

//递归获取某篇文章的所有评论
async function getReplies(author, permlink, res=[]) {
  let replies = await _this.steem.api.getContentRepliesAsync(author, permlink)
  let children = []
  replies.forEach(item => {
    res.push(item)
    if(item.children > 0){
      //把得到的子数据塞进 .child 中
      children.push(getReplies(item.author, item.permlink, item.child=[]))
    }
  })
  await Promise.all(children)
  return res
}
getReplies(author, permlink)
  .then(res => {
    // console.log(777, res)
    _this.replies = res
  })

查询并组织的数据结构如下:

child: Array(1)
   0: {…}
   length: 1
   __ob__: Observer {value: Array(1), dep: Dep, vmCount: 0}
   __proto__: Array 
children: 4

所有的子节点的数据都被塞进 .child 中,一层层嵌套。

利用递归组件显示

既然数据结构是递归的,那么就可以利用数据的特点直接递归显示。查了下Vue的一些用法,也是顺利搞定了。

//需要主组件和递归组件两个组件来完成
//主组件 Reply.vue
<template>
  <div class="reply">
    <div v-for="item in replies">
        <Replylist :parentmsg="item"></Replylist>
    </div>
  </div>
</template>

<script>
import Replylist from './Replylist'
export default {
  name: "Reply",
  data(){
    return {
      replies:[],
    }
  },
  components: {
    Replylist
  }
}
</script>

//递归组件 Replylist.vue
<template>
  <div class="item">
    @{{ parentmsg.author}} {{ parentmsg.body}}
    <ul v-if="parentmsg.child" class="child">
      <Replylist v-for="(item,index) in parentmsg.child" :parentmsg="item" :key="index"></Replylist>
    </ul>
  </div>
</template>
<script>
  export default {
    name: "Replylist",
    props: ['parentmsg']
  }
</script>

基本上就这么多了,就是递归的思想不好弄明白,这个过程不太直观。另外,查询评论挺花时间的,估计得要个1~3秒左右。而且它和文章不太相同,文章基本不会变化,没有太多实时的数据。评论是动态的,没办法用本地数据来处理。我在想,有没有更好的办法来实现。

Sort:  

测试下,11.10 8:36

11.11ok么

新方法如何呢?

小蒋辛苦了!

来自于 [WhereIn Android] (http://www.wherein.io)

还行,爱好!

收藏一下。

村长多过来指导工作!

共同进步~

Posted using Partiko iOS

Coin Marketplace

STEEM 0.19
TRX 0.16
JST 0.029
BTC 64536.58
ETH 2626.67
USDT 1.00
SBD 2.83