3.7 异步加载节点数据
3.7.1 官方文档
节点的数据是从后台进行获取的
3.7.2 编程步骤
技巧01:异步加载节点数据时init方法不用传递第三个参数
> 准备一个后台用于返回JSON格式的数据
技巧01:返回的JSON数据是一个列表,格式为
[ { "id": 1, "pId": 0, "name": "1 one" }, { "id": 2, "pId": 0, "name": "2 two" } ]
技巧02:三少偷懒,是利用json-server模拟的后台数据,哈哈;json-server
> 设置基本配置对象的async属性
setting = { view: { showLine: true, showIcon: true, fontCss: this.getFont }, data: { simpleData: { enable: true, idKey: 'id', pIdKey: 'pId' } }, callback: { onClick: this.onCzTreeOnClick }, async: { enable: true, url:"http://localhost:3000/data", type: "get", // autoParam:["id", "name=n", "level=lv"], // otherParam:{"otherParam":"zTreeAsyncTest"}, dataFilter: this.filter } };
> 编写响应数据处理方法
filter(treeId, parentNode,responseData) { console.log(responseData); if (responseData) { for(var i =0; i < responseData.length; i++) { responseData[i].name += "动态节点数据" + responseData[i].id; } } return responseData; }
3.7.3 代码总汇
{ "data": [ { "id": 1, "pId": 0, "name": "1 one" }, { "id": 11, "pId": 1, "name": "1.1 oneToOne" }, { "id": 12, "pId": 1, "name": "1.2 oneToTwo" }, { "id": 2, "pId": 0, "name": "2 two" } ] }
<ul class="ztree"><ul></ul>
import { Component, OnInit } from '@angular/core'; declare var $ : any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { setting = { view: { showLine: true, showIcon: true, fontCss: this.getFont }, data: { simpleData: { enable: true, idKey: 'id', pIdKey: 'pId' } }, callback: { onClick: this.onCzTreeOnClick }, async: { enable: true, url:"http://localhost:3000/data", type: "get", // autoParam:["id", "name=n", "level=lv"], // otherParam:{"otherParam":"zTreeAsyncTest"}, dataFilter: this.filter } }; // zNodes = [ // {id: 1, pId: 0, name: '1 一级标题', open: true, iconOpen:"assets/zTree/css/zTreeStyle/img/diy/1_open.png", iconClose:"assets/zTree/css/zTreeStyle/img/diy/1_close.png"}, // {id: 11, pId: 1, name: '1.1 二级标题', open: true, font:{'background-color':'skyblue', 'color':'white'}}, // {id: 111, pId: 11, name: '1.1.1 三级标题 -> 博客园1', url: 'http://www.cnblogs.com/NeverCtrl-C/', target: '_blank'}, // {id: 113, pId: 11, name: '1.1.1 三级标题 -> 博客园2', url: 'http://www.cnblogs.com/NeverCtrl-C/', target: '_self'}, // {id: 112, pId: 11, name: '1.1.2 三级标题 -> 单击', click: "alert('你单击了')"}, // {id: 12, pId: 1, name: '1.2 二级标题'}, // {id: 2, pId: 0, name: '2 一级标题'} // ] getFont(treeId, node) { return node.font ? node.font : {}; } filter(treeId, parentNode,responseData) { console.log(responseData); if (responseData) { for(var i =0; i < responseData.length; i++) { responseData[i].name += "动态节点数据" + responseData[i].id; } } return responseData; } onCzTreeOnClick(event, treeId, treeNode, clickFlag) { alert(treeNode.name); } constructor() { } ngOnInit() { console.log('打印输出jquery对象'); console.log($); console.log('但因输出zTree对象'); console.log($.fn.zTree); // $.fn.zTree.init($("#ztree"),this.setting,this.zNodes); $.fn.zTree.init($("#ztree"),this.setting); } }
内容版权声明:除非注明,否则皆为本站原创文章。