使用echarts显示树形组织架构

89 篇文章 0 订阅
31 篇文章 0 订阅
js代码 
function GetOrganization() {
        var data = "";
            var myChartOrganization = echarts.init(document.getElementById('divOrganization'));
            var labelOption = {
                normal: {
                    show: true,

                    formatter: '{c}  {name|{a}}',
                    fontSize: 16,
                    rich: {
                        name: {
                            textBorderColor: '#fff'
                        }
                    }
                }
            };

            // 指定图表的配置项和数据
        var option2 = {
            graphic: [
                {
                    type: 'image',
                    id: 'logo',
                    bounding: 'raw',
                    style: {
                        image: '../image/background3.jpg',
                        width: 1545,
                    }
                }
            ],
 
            series: [
                {
                    type: 'tree',

                    data: [data],

                    left: '2%',
                    right: '2%',
                    top: '8%',
                    bottom: '20%',

                    symbol: 'image://http://' + window.location.host + '/image/Dark_blue_button.png',//'emptyCircle',
                    symbolSize: [100, 30],
                    orient: 'vertical',

                    expandAndCollapse: false,
                    initialTreeDeptp:-1,
                    itemStyle: {
                        color: '#f56954',
                        borderColor: "#00c0ef",
                        borderWidth:8,
                    },
                    label: {
                        formatter: '{b}   ',
                        position: 'inside',
                        distance:5,
                        fontSize: 14,
                         color:"#FFF",
                    },

                    leaves: {
                        label: {
                            position: 'inside',
                            // rotate: -90,
                            verticalAlign: 'middle',
                            align: 'center',
                        },
                        itemStyle: {
                            color:"#00c0ef",
                        }

                    },

                    animationDurationUpdate: 750
                }
            ]              //  color: ['#007bff', '#dc3545','#2E90CD', '#FE0000']
        };

        // 使用刚指定的配置项和数据显示图表。

            myChartOrganization.showLoading(); // 加载动画

            myChartOrganization.setOption(option2);

            myChartOrganization.hideLoading();

            GetChartResult();

           function GetChartResult() {
               var ID = '1000';
                var ParentID = '0';
               
                var auto = myChartOrganization.getOption();

                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetOrganization","BaseData")',
                        //contentType: "application/json; charset=utf-8",
                    data: {
                        ID: ID,
                        ParentID:ParentID,
                    },
                    async: false,

                    dataType: "json",
                    success: function (data) {
                        //console.log(data)

                         var auto = myChartOrganization.getOption();

                        var data1 = data.replace(/ID/g, "value").replace(/OrganizationName/g, "name").replace(/CHILDREN/g, "children")
                        var data2 = data1.substring(0, data1.length - 1);
                        var data3 = data2.substring( 1,data1.length);

                        var objData = JSON.parse(data1)

                        auto.series[0].data = objData; //数据源
                        //auto.legend.data =legendData;
                        myChartOrganization.showLoading(); // 加载动画
                        myChartOrganization.setOption(auto, false);
                        myChartOrganization.hideLoading();

                        myChartOrganization.on('click', function (params) {
                            console.log('params')
                            console.log(params)
                            var name = params.name;
                            var seriesType = params.seriesType;
                            console.log(name + "\n" + seriesType);

                            if (params.data.children.length == 0) {


                                $('#txtBelongOrganizationID').val(params.value);
                                $('#txtBelongOrganizationName').val(params.name);

                                $('#' + SelectOrganizationID_ID).val($('#txtBelongOrganizationID').val());

                                $('#' + SelectOrganizationName_ID).val($('#txtBelongOrganizationName').val());

                            }
                            else {

                                $('#txtBelongOrganizationID').val('');
                                $('#txtBelongOrganizationName').val('');

                                $('#' + SelectOrganizationID_ID).val($('#txtBelongOrganizationID').val());
                                $('#' + SelectOrganizationName_ID).val($('#txtBelongOrganizationName').val());

                            }
                            $('#' + SelectOrganizationID_ID).trigger("change");
                        })

                    },
                    error: function (message) {
                        // alert(message);
                    }
                });
            }
    }
MVC controller代码
        public JsonResult GetOrganization(OrganizationModels om)
        {
            var resultmodel = new ResultModel<object>();
            try
            { 
                DataTable dt = Organizations.GetOrganization(om);
                List<OrganizationModels> ls = DataTableExtend.ToDataList<OrganizationModels>(dt);  
                string org = JsonConvert.SerializeObject(OrganizationModels.OrganizationRecursion(om.ParentID, ls));
                 
                return Json(org);
            }
            catch (MySqlException ex)
            { 
                resultmodel.ErrorCode = "1";
                resultmodel.Message = ex.Message;
                return Json(resultmodel);
            }
        }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace com.aaa.Models
{
    public class OrganizationModels
    {
        public string ID { get; set; } 
        public string OrganizationName { get; set; }
        public string ParentID { get; set; }  
        public List<OrganizationModels> CHILDREN { get; set; }
 

        public static List<OrganizationModels> OrganizationRecursion(string pid, List<OrganizationModels> obj)
        {
            List<OrganizationModels> lso = new List<OrganizationModels>(); 
            for (int i = 0; i < obj.Count; i++)
            {
                OrganizationModels om = new OrganizationModels();

                if (obj[i].ParentID == pid)
                { 
                    om.ID = obj[i].ID;
                    om.ParentID = obj[i].ParentID;
                    om.OrganizationName = obj[i].OrganizationName;
                    lso.Add(om);
                    om.CHILDREN = OrganizationRecursion(obj[i].ID, obj);
                } 
            }
             
            return lso;
        }
    }

   
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace com.aaa.Extend
{
    /// <summary>
    /// DataTable扩展方法类
    /// </summary>
    public static class DataTableExtend
    {
        /// <summary>
        /// DataTable转成List
        /// </summary>
        public static List<T> ToDataList<T>(this DataTable dt)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());

            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }

            foreach (DataRow item in dt.Rows)
            {
                T s = Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        try
                        {
                            if (!Convert.IsDBNull(item[i]))
                            {
                                object v = null;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                }
                                info.SetValue(s, v, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                        }
                    }
                }
                list.Add(s);
            }
            return list;
        }

        /// <summary>
        /// DataTable转成实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T ToDataEntity<T>(this DataTable dt)
        {
            T s = Activator.CreateInstance<T>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return default(T);
            }
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                if (info != null)
                {
                    try
                    {
                        if (!Convert.IsDBNull(dt.Rows[0][i]))
                        {
                            object v = null;
                            if (info.PropertyType.ToString().Contains("System.Nullable"))
                            {
                                v = Convert.ChangeType(dt.Rows[0][i], Nullable.GetUnderlyingType(info.PropertyType));
                            }
                            else
                            {
                                v = Convert.ChangeType(dt.Rows[0][i], info.PropertyType);
                            }
                            info.SetValue(s, v, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                    }
                }
            }
            return s;
        }

        /// <summary>
        /// List转成DataTable
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entities">实体集合</param>
        public static DataTable ToDataTable<T>(List<T> entities)
        {
            if (entities == null || entities.Count == 0)
            {
                return null;
            }

            var result = CreateTable<T>();
            FillData(result, entities);
            return result;
        }

        /// <summary>
        /// 创建表
        /// </summary>
        private static DataTable CreateTable<T>()
        {
            var result = new DataTable();
            var type = typeof(T);
            foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                var propertyType = property.PropertyType;
                if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    propertyType = propertyType.GetGenericArguments()[0];
                result.Columns.Add(property.Name, propertyType);
            }
            return result;
        }

        /// <summary>
        /// 填充数据
        /// </summary>
        private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
        {
            foreach (var entity in entities)
            {
                dt.Rows.Add(CreateRow(dt, entity));
            }
        }

        /// <summary>
        /// 创建行
        /// </summary>
        private static DataRow CreateRow<T>(DataTable dt, T entity)
        {
            DataRow row = dt.NewRow();
            var type = typeof(T);
            foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
            }
            return row;
        }
    }
}
 
数据库查询语句
        public static DataTable GetGoodOneOrganization(OrganizationModels om)
        {
            string sqlstr = @" SELECT DepartmentID AS ID,DepartmentName AS OrganizationName,ParentDepartmentID AS ParentID  FROM 
                                    (
                                       SELECT DepartmentID  , ParentDepartmentID,DepartmentName 
                                          FROM t_department 
                                             WHERE ParentDepartmentID IS NOT NULL
		                             ) rd,(SELECT @pid := @ID) pd
                                    WHERE FIND_IN_SET( ParentDepartmentID, @pid ) > 0 AND @pid := concat( @pid, ',', DepartmentID ); "; 
            MySqlParameter[] sqlParameter = new MySqlParameter[] {
                new MySqlParameter("ID",om.ID),
            };

            DataTable dt = MySqlHelper_.ExecuteDataTable(MySqlHelper_.GoodOneconnstr, sqlstr, sqlParameter);
            return dt;
        }

数据库内容

echarts展示效果

 

在Vue.js中使用ECharts绘制树形图并实现懒加载,通常需要以下几个步骤: 1. **安装依赖**: 首先,在项目中引入ECharts库和相关的Vue组件。你可以通过npm或yarn添加`echarts-for-vue`包: ```bash npm install echarts-for-vue @vue/echarts --save ``` 2. **配置数据结构**: 创建一个表示树形结构的数据模型,包含节点ID、名称、以及是否展开等属性。对于懒加载,可以设置一个标志表示节点是否已加载。 3. **创建组件模板**: 使用ECharts Vue插件创建一个自定义组件,比如`TreeChart.vue`: ```html <template> <div ref="chart" :style="{ height: '400px' }"></div> </template> <script> import { ECharts, registerComponent } from '@vue/echarts'; export default { components: { ECharts, }, data() { return { chart: null, treeData: [], // 按需填充懒加载树数据 loadedNodes: [], }; }, mounted() { this.initChart(); }, methods: { async initChart() { // 初始化图表,这里只是一个示例,实际操作需要根据数据动态构建 const options = { // ... 设置tree图的选项,包括分层、拖拽等 }; this.chart = this.$echarts.init(this.$refs.chart); this.chart.setOption(options); // 当用户滚动到某个未加载节点时,异步加载该节点及其子节点 this.chart.on('scroll', (params) => { if (!this.treeData.some((node) => this.loadedNodes.includes(node.id))) { const nodeToLoad = this.findNodeByScroll(params.position); // 根据滚动位置查找节点 await this.loadNode(nodeToLoad); } }); }, findNodeByScroll(position) { // 根据滚动位置查找对应的节点 // 实现细节取决于你的树数据结构和布局 }, loadNode(node) { // 异步加载节点和其子节点,例如通过API请求获取详细数据,然后更新treeData和loadedNodes // 这里仅做示例,实际处理可能会更复杂 const loadChildren = () => new Promise((resolve) => { setTimeout(() => { // 更新数据和状态 // ... resolve(); }, 1000); // 模拟延迟加载时间 }); loadChildren().then(() => { this.treeData.push(...node.children); this.loadedNodes.push(node.id); }); }, }, }; </script> ``` 这里假设`findNodeByScroll`方法根据页面滚动位置找到需要加载的节点,`loadNode`方法负责发送请求加载数据。 4. **在父组件中使用**: 将`TreeChart`组件添加到需要展示树形图的地方,并传入初始数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值