// pages/common/comTree/index.js /** value = [ { id: 1, name: '一级名称', children: [] } ] */ Component({ /** * 组件的属性列表 */ properties: { dataTree: { type: Array, value: [] }, selectKey: { // 选中的节点id type: String, value: '' }, isSelectLastNode: { //是否必须选中最后一节点 type: Boolean, value: false }, isOpenAll: { //是否展开全部节点 type: Boolean, value: false } }, observers: { 'dataTree': function(params) { let dataTree = JSON.parse(JSON.stringify(this.properties.dataTree)) var tree = this.findParent(dataTree,this.properties.selectKey,[]) params.forEach(v => { if(v.id == tree[0]){ v.open = true }else{ v.open = this.properties.isOpenAll // 是否展开 } }) this.setData({ tree:params }) } }, /** * 组件的初始数据 */ data: { tree: [] }, /** * 组件的方法列表 */ methods: { findParent(data, target, result) { for (let i in data) { let item = data[i] if (item.id == target) { //将查找到的目标数据加入结果数组中 //可根据需求unshift(item.id)或unshift(item) item.open = true result.unshift(item.id) return result } if (item.children && item.children.length > 0) { let ok = this.findParent(item.children, target, result) if (ok) { item.open = true result.unshift(item.id) return result } } } //走到这说明没找到目标 return false }, isOpen(e) { const open = 'tree[' + e.currentTarget.dataset.index + '].open' this.setData({ [open]: !this.data.tree[e.currentTarget.dataset.index].open }) }, select(e) { const item = e.currentTarget.dataset.item if(this.properties.isSelectLastNode) { // console.log(item) this.triggerEvent('select', { item: item }, { bubbles: true, composed: true }) // if (!item.children || item.children.length == 0) { // this.triggerEvent('select', { item: item }, { bubbles: true, composed: true }) // } else { // this.triggerEvent('select', { tips: '必须选择最后一个节点' }, { bubbles: true, composed: true }) // } } else { this.triggerEvent('select', { item: item }, { bubbles: true, composed: true }) } } } })