首页 > 其他分享 >自增树形组件

自增树形组件

时间:2023-02-03 14:11:14浏览次数:32  
标签:自增 console log children item 树形 组件 data id

<view class="tree_Box">
      
  <!-- 有多个 -->

   <view class="tree" a:for="{{datas}}" a:key="{{item.id}}">

  
     <view class="tree_childern_item"  a:if="{{item.children.length>0}}" >
      <view class="tree_item"  >  
        <view class="tree_item_left" onTap="del" data-item='{{item}}'>
          <image mode="scaleToFill" src="/assets/xym/del.png" class="img" a:if="{{!item.hiddenDel}}"/>
        </view>
        <view class="tree_item_middle">
          <input className="list-item-input" placeholder-class="input-placeholder"  placeholder="请输入" 
          type="text" value="{{item.value}}" onInput="onItemInput" data-idx="{{item.id}}"></input>
   
      
          <!-- <form-item
                  label=""
                  name="{{`id${item.id}`}}"
                  required
                  form="{{form}}">
                  <input-item form="{{form}}" placeholder="请填写" />
              </form-item> -->
        </view>
        
  
        <view  class="tree_item_right">
          <view class="addSame" style="margin-right:32rpx" onTap="addSame" data-item='{{item}}'>
           +同级
          </view>
          <view class="addChildren"  onTap="addChild" data-item='{{item}}' a:if="{{item.level<2}}">
           +下级
          </view>
       </view>
        <!-- {{item.name}} -->
       


      </view>
      <view class="tree_childern_box">
        <!-- {{form}} {{onDelData}}  -->
        <tree datas={{item.children}}  form="{{form}}" onDelData="del"  onAddSameData="addSame"  onAddChildData="addChild"> </tree>
      </view>
    
     </view>

     
     <view class="tree_item"  a:else a:key="{{item.id}}">  
      <view class="tree_item_left" onTap="del" data-item='{{item}}'>
        <image mode="scaleToFill" src="/assets/xym/del.png" class="img" a:if="{{!item.hiddenDel}}"/>
      </view>
      <view class="tree_item_middle">
        <input className="list-item-input" placeholder-class="input-placeholder"  placeholder="请输入" 
        type="text" value="{{item.value}}" onInput="onItemInput" data-idx="{{item.id}}"></input>
 

        <!-- <form-item
                label=""
                name="{{`id${item.id}`}}"
                required
                form="{{form}}">
                <input-item form="{{form}}" placeholder="请填写" />
            </form-item> -->
      </view>
      

            <view  class="tree_item_right">
               <view class="addSame" style="margin-right:32rpx" onTap="addSame" data-item='{{item}}'>
                +同级
               </view>
               <view class="addChildren"  onTap="addChild" data-item='{{item}}' a:if="{{item.level<2}}">
                +下级
               </view>
            </view>
      <!-- {{item.name}} -->
    </view>
   
 
   </view>

     </view>
Component({
  data: {
  
    isConfirm: false, // 确认是否可点击
    
   
  },
  props: {
    form:'', 
    datas: [],
    selectShow: false, // 选择面板是否展示
    onDelData:()=>{},
    onAddSameData:()=>{},
    onAddChildData:()=>{}
  },
  didMount() {
    this.$page.tree = this; // 通过此操作可以将组件实例挂载到所属页面实例上
    const { list } = this.props;
    // console.log('[ didMount ] >',  this,this.props.datas)
   
  },
  didUpdate(prevProps, prevData) {
    const { selectValue, list } = this.props;
    console.log('[ didUpdate ] >',  this,this.props.datas)

    // 面板状态改变的时候数据的重新渲染
    // console.log('[ didUpdate ] >', this.props)
    // this.setData({form:this.props.form})
  },
  didUnmount() { 
  
  },
  methods: {
    // 输入框输入
  onItemInput(e) {
    const value = e.detail.value;
    const { idx } = e.target.dataset;
    console.log('[ e ] >', e)
    this.$page.treePage.changeValues(idx,value,this.props.form)

  },

     del(e){
       const {item} = e.target.dataset
      
        //  console.log('[ delData ] >',  this.props,this.$page,item)
        this.$page.treePage.delData(item,this.props.form)
      //  this.props.onDelData(item)
     },
     addSame(e){
      const {item} = e.target.dataset
      // console.log('[ e ] >',  this.props)
      this.$page.treePage.addSameData(item,this.props.form)

    },
    addChild(e){
      const {item} = e.target.dataset
      // console.log('[ e ] >', e)
      // this.props.onAddChildData(item)
      this.$page.treePage.addChildData(item,this.props.form)


    }
  }
});
.tree_item{
  height: 96rpx;
  display: flex;
  justify-content: space-between;
  line-height: 96rpx;
  border-bottom: 2rpx  solid rgba(241,241,241,1);;
  }
  .tree_childern_box {
    margin-left: 30rpx;
  }
  .tree{
    font-family: PingFangSC-Regular;
font-size: 32rpx;
color: #25282E;
font-weight: 400;
  }

  .tree_item{
    display: flex;
    align-items: center;

   
  }
  .tree_item .tree_item_left{
    width: 32rpx;
height: 32rpx;
margin-right: 10rpx;
display: flex;
justify-content: center;
align-items: center;
  }
  .img{
    width: 32rpx;
    height: 32rpx;
  }
  .tree_item .tree_item_middle{
   flex: 1;
   display: flex;
justify-content: center;
align-items: center;
  }
  .tree_item .tree_item_right{
    width: 160rpx;
    display: flex;
    height: 100%;

   }
 
   .addSame, .addChildren{
   
    font-family: PingFangSC-Regular;
    font-size: 24rpx;
    color: #1F90FB;
   }
   .tree_item .amd-form-item{
    padding :0 !important
   }
   .tree_item .list-item-input{
     text-align: left !important;
     width: 100%;
     max-width:none !important
   }
<tree form="{{form1}}" datas="{{datasClass}}"   onDelData="delData"  onAddSameData="addSameData"  onAddChildData="addChildData"> </tree>
 
import { getUserNameReplace, getIdCardReplace, getPhoneReplace } from '/utils/service/serviceConfig'
import EnumGlobal from '/utils/enumGlobal';
import { queryQrContentByIdNumber } from '/utils/service/pjm'

import {
  treeFindPath,
  findNodeInTree,
  updateNodeInTree,
  appendNodeInTree,
  removeNodeInTree
} from '/utils/xym';

const initialValues = {  // 根据id更新值,传值
  account: '',
  password: '',
};
const a = [
  {
    id: 1, name: '一年级', hiddenDel: true, children: [
      {
        id: 2, name: '一年级1班', children: [
          {
            id: 6, name: '一年级1班01', children: [
              { id: 10, name: '一年级1班001' }
            ]
          }
        ]
      },
      { id: 3, name: '一年级2班' },
      { id: 4, name: '一年级3班' },
    ]
  },
  {
    id: 5, name: '二年级', children: [
      { id: 11, name: '二年级1班' }
    ]
  },
  {
    id: 7, name: '三年级', children: [
      { id: 8, name: '三年级1班' }
    ]
  }
]

Component({
  data: {
    form1: 'form1',
    form2: 'form2',

    datasClass: [
      {
        id: 1, value: '一年级', hiddenDel: true,isSelf:true,level:1, children: [
          { id: 2, value: '一(1)班',isSelf:true, level:2, },

        ]
      },

    ],
    datasOrization: [
      { id: 1, value: '门卫', hiddenDel: true,isSelf:true,level:1,  },

    ],
    formValues: {}

  },
  didMount() {
    this.$page.treePage = this; // 通过此操作可以将组件实例挂载到所属页面实例上
    this.getInitTree()
  },
  didUpdate(prevProps, prevData) {
    if (JSON.stringify(prevProps.detail) !== JSON.stringify(this.props.detail)) {
      this.getInitTree()
    }
  },
  methods: {
    getInitTree() {
      let organizationDTOList = my.getStorageSync({
        key: `organizationDTOList`
      });
      console.log('organizationDTOList增加',organizationDTOList);
      if (organizationDTOList.data) {
       organizationDTOList.data.classList[0].hiddenDel=true
       organizationDTOList.data.orization[0].hiddenDel=true
        this.setData(
          {
            datasClass: organizationDTOList.data.classList || [],
            datasOrization: organizationDTOList.data.orization || [],
          })
      }
     
     
  
    
    },

    delData(item, formType) {
      console.log('[ item ] >', item)
      if (item['children'] && item['children'].length > 0) {
        my.showToast({ content: "有子级内容,不允许删除" })
      } else {
        let datas = formType === 'form1' ? [...this.data.datasClass] : [...this.data.datasOrization]
        removeNodeInTree(datas, item.id)
        console.log('[ datas ] >', datas)

        if (formType === 'form1') {
          this.setData({ datasClass: JSON.parse(JSON.stringify(datas)) })

        } else {
          this.setData({ datasOrization: JSON.parse(JSON.stringify(datas)) })

        }
      }
    },
    addSameData(item, formType) {
      console.log('[ item ] >', item)
      let datas = formType === 'form1' ? [...this.data.datasClass] : [...this.data.datasOrization]
      let arrParent = treeFindPath(datas, data => data.id === item.id, "id");
      //     console.log('[ arr ] >', arr)
      let obj = { id: this.guid(), name: '',isSelf:true,level:item.level }
      if (arrParent.length <= 1) { // 第一级
        datas.push({...obj})
      } else {
        findNodeInTree(datas, arrParent[arrParent.length - 2], (item, index, arr) => {
          item.children ? item.children.push({...obj}) : item.children = [{...obj}]

        })

      }
      console.log('[ DATAS ] >', datas,this.formatData(datas,1,0))

      if (formType === 'form1') {
        this.setData({ datasClass: JSON.parse(JSON.stringify(datas)) })

      } else {
        this.setData({ datasOrization: JSON.parse(JSON.stringify(datas)) })

      }
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    addChildData(item, formType) {
      console.log('[ item ] >', item)
      let datas = formType === 'form1' ? [...this.data.datasClass] : [...this.data.datasOrization]
      let obj = { id: this.guid(), name: '',isSelf:true,level:item.level+1 }
      let trees = appendNodeInTree(item.id, datas, obj)
      console.log('[ datas ] >', JSON.stringify(trees))
      if (formType === 'form1') {
        this.setData({ datasClass: JSON.parse(JSON.stringify(trees)) })

      } else {
        this.setData({ datasOrization: JSON.parse(JSON.stringify(trees)) })

      }
    },
    changeValues(id, value, formType) {
      let datas = formType === 'form1' ? [...this.data.datasClass] : [...this.data.datasOrization]
      findNodeInTree(datas, id, (item, index, arr) => {
        item['value'] = value
      })
      console.log('[ id ] >', id, value, datas)

      if (formType === 'form1') {
        this.setData({ datasClass: JSON.parse(JSON.stringify(datas)) })

      } else {
        this.setData({ datasOrization: JSON.parse(JSON.stringify(datas)) })

      }

    },
    validateFields(data, callback) {
      if (data) {
        for (let i = 0; i < data.length; i++) {
          if (!data[i].value) { // 没有值
            return callback(data[i], i, data)
  
          }
          if (data[i].children) {
            this.validateFields(data[i].children, callback)
          }
        }
      }
     
    },
    formatData(data,pLevel=1,type) {
      let temparr = [];
      data.forEach((item)=>{    
                let obj= {...item,name:item.value,level:pLevel,type:type,organizationDTOList: item.children? this.formatData(item.children,pLevel+1,type) : null}
                temparr.push(obj)
          
      })
      console.log('增加formatData',data);
      return temparr;
  },


   async submitClass() { // 提交树数据
      
      console.log('[ datasClass datasOrization] >', this.data.datasClass, this.data.datasOrization)
      let flag = true
      this.validateFields(this.data.datasClass, (item, index, data) => {
        console.log('[ item ] >', item)
        flag = false // 
        my.showToast({ content: "班级组织不能为空值,请填写完整或者删除空值项" })
      })
      this.validateFields(this.data.datasOrization, (item, index, data) => {
        console.log('[ item ] >', item)
        flag = false // 
        my.showToast({ content: "其他组织不能为空值,请填写完整或者删除空值项" })
      })

      // 递归便利重构数据,
    // let allDatas=[...this.formatData(this.data.datasClass,1,0),...this.formatData(this.data.datasOrization,1,1)]
    //  console.log('合并数据,formatData',allDatas);

      return new Promise((resolve, reject) => {
        if (flag) {
          // 缓存数据
          my.setStorageSync({
            key: `organizationDTOList`,
            data: {classList:this.formatData(this.data.datasClass,1,0),orization:this.formatData(this.data.datasOrization,1,1)}
          })
         
          resolve(true)
        } else {
          reject(false)
        }
       
      })
    }
  },


});



//公共方法文件js
const removeNodeInTree =(treeList, id) =>{ // 通过id从数组(树结构)中移除元素
  if (!treeList || !treeList.length) {
    return
  }
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].id === id) {
      treeList.splice(i, 1);
      console.log('[ i ] >', i)
      break;
    }
    removeNodeInTree(treeList[i].children, id)
  }
}
const appendNodeInTree =(id, tree, obj)=> {
  tree.forEach(ele=> {
    if (ele.id === id) {
      ele.children ? ele.children.push(obj) : ele.children = [obj]
    } else {
      if (ele.children) {
       appendNodeInTree(id, ele.children, obj)
      }
    }
  })
  console.log('[ tree ] >', tree)
  return tree
}
const updateNodeInTree=(treeList,id, obj) =>{
  if (!treeList || !treeList.length) {
    return;
  }
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].id == id) {
      treeList[i]= obj;
      break;
    }
    updateNodeInTree(treeList[i].children,id,obj);
  }
}
const findNodeInTree= (data, key, callback)=>  {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id == key) {
      return callback(data[i], i, data)
    }
    if (data[i].children) {
     findNodeInTree (data[i].children, key, callback)
    }
  }
}
 
// // 所查找到的节点要存储的方法
// let Obj={}
// findNodeInTree(data, key, (item, index, arr) => {
//   Obj = item
// })

// // 此时就是Obj对应的要查找的节点
// console.log(Obj)

const treeFindPath=(tree, func, field = "", path = []) =>{
  if (!tree) return []
  for (const data of tree) {
    field === "" ? path.push(data) : path.push(data[field]);
    if (func(data)) return path
    if (data.children) {
      const findChildren =treeFindPath(data.children, func, field, path)
      if (findChildren.length) return findChildren
    }
    path.pop()
  }
  return []
}
//校验社会信用代码
function checkSocialCreditCode(Code) {
  var patrn = /^[0-9A-Z]+$/;
  if ((Code.length != 18) || (patrn.test(Code) == false)) {
    return false;
  }
  else {
    var Ancode;//统一社会信用代码的每一个值
    var Ancodevalue;//统一社会信用代码每一个值的权重
    var total = 0;
    var weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
    var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
    for (var i = 0; i < Code.length - 1; i++) {
      Ancode = Code.substring(i, i + 1);
      Ancodevalue = str.indexOf(Ancode);
      total = total + Ancodevalue * weightedfactors[i];
    }
    var logiccheckcode = 31 - total % 31;
    if (logiccheckcode == 31) {
      logiccheckcode = 0;
    }
    var Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
    var Array_Str = Str.split(',');
    logiccheckcode = Array_Str[logiccheckcode];
    var checkcode = Code.substring(17, 18);
    if (logiccheckcode != checkcode) {
      return false;
    }
    return true;
  }
}

/**
 * 学校类型学校类型(0:幼儿园,1:小学,2:中学,3:大学,4:校外培训学校,5:中专职高技校,6:其他)
 */
const schoolType = [
  {
    label: '幼儿园',
    value: '0'
  },
  {
    label: '小学',
    value: '1'
  },
  {
    label: '中学',
    value: '2'
  },
  {
    label: '大学',
    value: '3'
  },
  {
    label: '校外培训学校',
    value: '4'
  },
  {
    label: '中专职高技校',
    value: '5'
  },
  
  {
    label: '其他',
    value: '6'
  }
];
export {
  treeFindPath,
  findNodeInTree,
  updateNodeInTree,
  appendNodeInTree,
  removeNodeInTree,
  checkSocialCreditCode,
  schoolType
  
  
}

 

标签:自增,console,log,children,item,树形,组件,data,id
From: https://www.cnblogs.com/lanlanwb/p/17089051.html

相关文章