vue+vant 封装menu组件—-Tree型结构(递归)

  • Post author:
  • Post category:vue



父父组件:

    <template>
		<van-popup
	      v-model="show"
	      closeable
	      close-icon-position="top-left"
	      position="right"
	      :style="{ width: '100%',height: '100%' }">
	        <ReportListMenu :MenuData="MenuData"></ReportListMenu>
	    </van-popup>
	</template>
	<script>
		// 递归组件无法直接通过$emit()传值给父组件
		import Bus from '@/components/XXX/bus'
		import ReportListMenu from '@/components/XXX/ReportListMenu'
		export default {
			components: {
			    ReportListMenu
			 },
			data (){
				return {
					show: false,
					MenuData: []  // 菜单栏的数据(树形结构的数据)
				}
			},
			created() {
			    Bus.$on('clickmenuhandle', categoryId => {  
			        // 拿到的子组件的值(这里是categoryId)可以to do something
			    }); 
			  },
		}
	</script>


父组件:

<template>
  <div class="report_menu">
    <div class="menu_list" v-if="MenuData">
      <ReportMenuChildren
        v-for="(item, index) in MenuData"
        :key="index" :col="item"></ReportMenuChildren>
    </div>
  </div>
</template>
<script>
import ReportMenuChildren from '@/components/xxxxx/ReportMenuChildren'
export default {
  components: {
    ReportMenuChildren
  },
  props: ['MenuData']
}
</script>


子组件:

<template>
  <van-cell-group class="menuList">
    <van-cell
      :title="col.name"
      @click="menuListHandle(col)">
      <van-icon name="arrow" v-if="col.children.length > 0" />
    </van-cell>
    <div :class="show?'':'childNode'" v-if="col.children">
    	// report-menu 根据下面的name的值
      <report-menu v-for="(item, index) in col.children"
      :key="index"
      :col="item"></report-menu>
    </div>
  </van-cell-group>  
</template>
<script>
import { Toast } from 'vant'
import Bus from '@/components/xxxxx/bus'
export default {
  name: 'ReportMenu',
  props: {
    col: {
      type: Object
    }
  },
  data () {
    return {
      show: false
    } 
  },
  methods: {
    menuListHandle (data) {
      if (data.type === 1) {
        if (data.children.length === 0) {
          Bus.$emit('clickmenuhandle', data.id);  
        } else {
          this.show = !this.show
        } 
      } else {
        Toast.fail('此分类不可选')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .childNode{
      display: none;
    }
</style>



版权声明:本文为weixin_41144016原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。