vue 递归组件实现目录树,数据处理

vue 递归组件实现目录树,数据处理

我这个是移动端的目录树 代码都是通用的
第一次发表文章,话不多说直接上代码 样式可以自己调整

vue 递归组件实现目录树,数据处理_第1张图片

子组件ChapterTree.vue

子组件ChapterTree.vue
<template>
  <div>
    <div class="list-item" v-for="(item, index) in chapterList" :key="index">
      <div class="item-name">
        <span @click.stop="openMenu(item, index)">
          {{item.nodeName}}
          
          <van-icon
            v-if="item.children && item.children.length > 0"
            :name="item.expanded ? 'arrow-up':'arrow-down'"
          />
        span>

      div>
      <div
        :class="item.expanded ? 'open':'close'"
        class="children-item"
        v-if="item.children"
      >
      
        <ChapterTree
          :chapterList="item.children"
          type="detail"
          @close="close"
        />
      div>
    div>
  div>
template>
<script>
export default {
  name: 'ChapterTree',
  props: {
    chapterList: {
      type: Array,
      default: () => ([])
    },
    cId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      arrray: this.chapterList,
      showMenu: false
    }
  },
  methods: {
    openMenu (item) {
      if (item.children.length > 0) {
        item.expanded = !item.expanded
      } else {
        this.$router.push(
          { path: `要跳转的路径` }
        )
        this.close()
      }
    },
    close () {
      this.$emit('close')
    }
  }
}
script>

在父组件ChapterList.vue中调用子组件ChapterTree

父组件ChapterList.vue
<template>
  <div class="chapter">
    <div class="item-name">
      <span class="chapter-tip">共{{chapterDetail.chapterNum}}章节span>
    div>
    ChapterTree>
  div>
template>
<script>
import {
  getKnowledgeDetail,
  getTree
} from '@/api/knowledge'
import ChapterTree from './components/chapterTree'
export default {
  name: 'ChapterList',
  components: {
    ChapterTree
  },
  data () {
    return {
      chapterList: [] //后台请求回来的数据
    }
  },
  watch: {
    cId (newVal) {
      this.getTree()
    }
  },
  created () {
    this.getTree()// 获取目录树数据
  },
  methods: {
    getTree () {
      getTree({ collectionId: this.knowledgeId })
        .then(res => {
          this.chapterList = this.dealTree(res.data)
        })
        .catch(err => {
          console.log(err, '错误')
        })
    },
    //递归处理目录数据
    dealTree (menuData) {
      const arr = []
      for (let i = 0; i < menuData.length; i++) {
        const item = menuData[i]
        if (item.children && item.children.length) {
        //如果又自己数据 加一个字段 以便于控制菜单展收
          item.expanded = false
          item.children = this.dealTree(item.children)
        } else {
          item.children = []
        }
        arr.push(item)
      }
      return arr
    },
    close () {
      this.$emit('close')
    }
  }
}
script>

有问题请留言哦~~~~

你可能感兴趣的:(vue)