Vue3 封装Tree树形组件,且只支持单选

App.vue



<script setup>
import HelloWorld from './components/HelloWorld.vue'
import Tree from './components/Tree.vue'
import Panel from './components/Panel.vue'

import { provide, ref} from 'vue'
function isExceedThirtydays(value) {
  console.log(new Date(value).getTime());
  let timetamp = (new Date().getTime() - new Date(value).getTime()) >= 30 * 24 * 60 * 60 * 1000
  return timetamp
}
console.log(isExceedThirtydays("2023-12-17 09:46:56"));

const list = ref([
  {
    id:1,
    parentId:null,
    name:'qwerqwe',
  },
  {
    id:12,
    parentId:1,
    name:'qweradsfa',
  },
  {
    id:13,
    parentId:1,
    name:'wuliheadsfasdfihei',
  },
  {
    id:2,
    parentId:null,
    name:'技术部',
  },
  {
    id:21,
    parentId:2,
    name:'前端部门',
  },
  {
    id:22,
    parentId:2,
    name:'前端部门',
  },
  {
    id:222,
    parentId:22,
    name:'前端一级',
  },
  {
    id:223,
    parentId:22,
    name:'前端2级',
  },
  {
    id:224,
    parentId:22,
    name:'前端3级',
  },
])


function deepToTree(data,parentId){
  if(data.length > 0){
    return data.filter(item => item.parentId === parentId).map(item => {
      item.checked = false
      item.children = deepToTree(data,item.id)
      if(item.children.length){
        item.isClick = false
      }else {
        item.isClick = true
      }
      return item
    })
  }else{
    return []
  }
}
function changeTreeData(list,selectedId){
  if(list.length > 0){
    list.forEach(item => {
      if(item.id ===selectedId){
        item.checked = true
      }else {
        item.checked = false
      }
      if(item.children.length > 0){
        changeTreeData(item.children,selectedId)
      }
    });
  }
}
function changeSelectedRadio(item){
  changeTreeData(data.value,item.id)
  console.log(data.value,'xxxx');
}
provide('changeSelectedRadio',changeSelectedRadio)
const data =ref(deepToTree(list.value,null))
</script>

<template>
  <Tree :list="data"></Tree>
</template>

<style scoped>

</style>

Tree.vue


<template>
    <div class="containerz" v-if="list.length > 0" v-for="(item,index) in list" :key="item.id">
        <input type="checkbox" @click="change(item)" :checked="item.checked" :disabled="!item.isClick">{{item.name}}
        <div class="child" v-if="item.children.length > 0">
            <Tree :list="item.children"></Tree>
        </div>
    </div>
</template>
  
<script lang="ts" setup>
import { PropType, ref, watch, computed,inject } from 'vue'
const props = defineProps({
    list:{
        type:Array<any>,
        default:()=>[]
    }
})
const change= inject('changeSelectedRadio')
</script>
  
<style scoped lang="scss">
.containerz {
    text-align: start;
    .child {
        margin-left: 10px;
    }
}
   /* 未选中状态 */
//    input[type="checkbox"]:not(:checked) {
//       /* 添加灰色样式 */
//       filter: grayscale(100%);
//       /* 设置不可点击 */
//       pointer-events: none;
//     }

</style>

你可能感兴趣的:(vue.js,前端)