在开发中,有时候会遇到展示一些人物关系,上下级关系等相关需求,使用树状图可以清晰的表达出来
首先看下目录结构
- component
- echarts
- ec-canvas.js
- ec-canvas.json
- ec-canvas.wxml
- ec-canvas.wxss
- echarts.min.js
- wx-canvas.js
- pages
- treeView
- treeView.js
- treeView.json
- treeView.wxml
- treeView.wxss
- app.js
- app.json
………………
首先,将echarts 以组件的形式放到项目里来,大家可以去ECharts 的微信小程序版本去下载资源,然后放到项目中来
下面看下页面
import * as echarts from '../../component/graph/echarts.min.js';
let chart = null;
Page({
/**
* 页面的初始数据
*/
data: {
data: {
id: 1,
name: 'A',
intro: '这是A',
children: [
{
id: 2,
name: 'B',
intro: '这是B',
},
{
id: 3,
name: 'C',
intro: '这是C',
children: [
{
id: 5,
name: 'E',
intro: '这是E',
},
{
id: 6,
name: 'F',
intro: '这是F',
children: [
{
id: 7,
name: 'G',
intro: '这是G',
},
{
id: 8,
name: 'H',
intro: '这是H',
}
]
}
]
},
{
id: 4,
name: 'D',
intro: '这是D',
children: [
{
id: 9,
name: 'K',
intro: '这是K',
},
{
id: 10,
name: 'L',
intro: '这是L',
children: [
{
id: 11,
name: 'm',
intro: '这是m',
},
{
id: 12,
name: 'n',
intro: '这是n',
}
]
}
]
}
]
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.initChart()
},
initChart() {
this.ecComponent = this.selectComponent('#mychart-dom-bar')
this.ecComponent.init((canvas, width, height) => {
let data = this.data.data;
let id = data.id
chart = echarts.init(canvas, null, {
width: width,
height: height
});
canvas.setChart(chart);
let option = {
tooltip: {
show: true,
trigger: 'item',
triggerOn: 'click',
formatter: function (params) {
// console.log(params)
return params.data.intro
},
position: function (pos, params, dom, rect, size) {
// console.log(pos)
// 鼠标在左侧时 tooltip 显示到右侧,鼠标在右侧时 tooltip 显示到左侧。
var obj = { top: pos[1] + 3, right: size.viewSize[0] - pos[0] + 8 };
if (params.data.id == id) {
obj = { top: pos[1] + 3, left: pos[0] + 8 };
}
return obj;
}
},
series: [
{
type: 'tree',
data: [data],
top: '5%',
left: '5%',
bottom: '5%',
right: '5%',
symbolSize: 12,
// edgeShape: 'polyline', // 直线
// orient: 'vertical', //竖着
label: {
position: 'right',
verticalAlign: 'bottom',
align: 'left',
fontSize: 12
},
leaves: {
label: {
position: 'left',
verticalAlign: 'bottom',
align: 'right',
fontSize: 12
}
},
expandAndCollapse: true,
animationDuration: 550,
animationDurationUpdate: 750
}
]
};
chart.setOption(option);
chart.on('click', function (params) {
// console.log(params)
});
return chart;
})
},
})
{
"usingComponents": {
"echart": "../../component/graph/ec-canvas"
},
"navigationBarTitleText": "treeView"
}
最终实现效果:
END !