ztreeパッケージのツリー構造vueコンポーネント

15811 ワード

まず効果図を1枚ください.
ztree封装的树结构vue组件_第1张图片
1.z-treeプラグインダウンロードアドレスhttp://www.treejs.cn/v3/main.php#_zTreeInfo
2.ダウンロードが完了したら、プロジェクトにプラグインを入れてmian.jsに導入すればいい
ztree封装的树结构vue组件_第2张图片
//main.js   

import './plugins/zTree/jquery.ztree.all.js'
import './plugins/zTree/jquery.ztree.core.js'
import './plugins/zTree/jquery.ztree.excheck.js'
import './plugins/zTree/jquery.ztree.exedit.js'
import './plugins/zTree/jquery.ztree.exhide.js'

3.ztreeコンポーネント内部コード



// import fuzzysearch from "@/plugins/fuzzysearch.js";
export default {
    name: 'ztree',
    data () {
        return {
			inputval: '',
			prid: '',
			ztreedata: '',
			addtype1: true,
			addchild1: true
        }
	},
	props: ['treedata','addtype','addchild'],
    components: {
	},
	watch: {
		immediate: true,
		treedata(newval, oldval) {
			this.ztreedata = newval;
			this.szTree();
		}
	},
    created() {

    },
    mounted() {
		this.szTree();
    },
    methods: {
		shauxin() {
			this.$emit('shuaxin')
		},
		szTree: function(iname) {
			var setting = {
				view: {
					addHoverDom: this.addtype===false||this.addchild===false?false:this.addHoverDom,
					removeHoverDom: this.removeHoverDom,
					selectedMulti: false,
					addDiyDom: this.addDiyDom,
					// showIcon: false,
					showLine: true,
				},
				edit: {
					enable:  this.addtype===false?false:true,
					// showRenameBtn: true,
					renameTitle: "      ",
					removeTitle: "    ",
					drag: {
						prev: this.canPrev,
						next: this.canNext,
						inner: true
					}

				},
				callback: {
					onClick: this.zTreeOnClick,
					beforeDrag: this.beforeDrag,
					beforeDrop: this.beforeDrop, //                     
					onNodeCreated: this.zTreeOnNodeCreated, //   
					beforeEditName: this.zTreeBeforeRename, //    
					beforeRemove: this.zTreeBeforeRemove //    
				},
				data: {
					key:{
						name:"catalogName"
					},
					simpleData: {
						enable: true,
						idKey : "dataSourceGroupId",
						pIdKey : "parentDSource",
						rootPId : null
					}
				},
			};
			$.fn.zTree.init($("#treeDemo"), setting, this.ztreedata);
			this.fuzzySearch('treeDemo', '#key', null, true); //         
		},
		//         
		addHoverDom: function(treeId, treeNode) {
			var _this = this;
			// console.log(treeNode)
			// if(treeNode.parentDSource!=null) {
			// 	$("#" + treeId + " .button.edit").hide();
			// 	$("#" + treeId + " .button.remove").hide();
			// }
			//                 
			if (treeNode.type == 0) {
				$("#" + treeId + " .button.add").hide(); //      
				$("#" + treeId + " .button.edit").hide();
				$("#" + treeId + " .button.remove").hide();
			} else {
				//    
				var sObj = $("#" + treeNode.tId + "_span");
				if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
				var addStr = "<span class='button add' id='addBtn_" + treeNode.tId +
					"'title='      ' onfocus='this.blur();'></span>";
				sObj.after(addStr);    //        
				var btn = $("#addBtn_" + treeNode.tId);
				$('.ztree li span.button.add').css({
					'margin-left': '2px',
					'margin-right': '-1px',
					'background-position': '-144px 0',
					'vertical-align': 'top',
				})
				if (btn) btn.bind("click", function() {
					_this.$emit('addtreeNode', {'treeNode': treeNode})
				});
			}
		},
		//       
		removeHoverDom(treeId, treeNode) {
			$("#addBtn_" + treeNode.tId).unbind().remove();
		},
		//       ,    
		addDiyDom: function(treeId, treeNode) {
			var spantxt = $("#" + treeNode.tId + "_span").html();
		},
		//              
		canPrev: function(treeId, nodes, targetNode) {
			console.log("targetNode", targetNode);
			var pNode = targetNode.getParentNode();
			if (pNode && pNode.dropInner === false) {
				return false;
			}
			if (!targetNode.parentDSource && nodes[0].type == 0) {
				return false;
			}
			return true;
		},
		//             
		canNext: function(treeId, nodes, targetNode) {
			if (!targetNode.parentDSource && nodes[0].type == 0) {
				return false;
			}
			return true;
		},
		//           
		beforeDrag: function(treeId, treeNodes) {
			return false;
			// return true;
		},
		//      
		beforeDrop: function(treeId, treeNodes, targetNode, moveType) {
			console.log(targetNode);
			this.prid = treeNodes[0].parentDSource ? treeNodes[0].parentDSource : "";
			if (targetNode == null)
				return false;
			var newPrid = targetNode.dataSourceGroupId
			if (targetNode.type == 0) {
				return false;
			}
			var msid = treeNodes[0].dataSourceGroupId;
			var ypid = this.prid; //     ID
			var xpid = newPrid; //     ID
			var type = treeNodes[0].type; //  ,0    ,1   

			if (this.prid == newPrid) {
				xpid = "";
			}
			//       
			var zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
			var node = zTree_Menu.getNodeByParam("id", ypid);
		},
		//     
		zTreeBeforeRename: function(treeId, treeNode, newName, isCancel) {
			this.$emit('zTreeBeforeRename',{'treeNode':treeNode});
			return false;
		},
		//   
		zTreeBeforeRemove: function(treeId, treeNode) {
			this.$emit('removeTreeNode',{'treeId': treeId, 'treeNode': treeNode})
			return false;
		},
		//      
		zTreeOnClick: function(event, treeId, treeNode) {
			this.$emit('zTreeOnClick',{'treeNode':treeNode});
		},
		//      
		addzTreeOne: function(){
			this.$emit('addzTreeOne');
		},
		//       
		fuzzySearch(zTreeId, searchField, isHighLight, isExpand){
			var zTreeObj = $.fn.zTree.getZTreeObj(zTreeId);//get the ztree object by ztree id
			if(!zTreeObj){
				alert("fail to get ztree object");
			}
			var nameKey = zTreeObj.setting.data.key.name; //get the key of the node name
			isHighLight = isHighLight===false?false:true;//default true, only use false to disable highlight
			isExpand = isExpand?true:false; // not to expand in default
			zTreeObj.setting.view.nameIsHTML = isHighLight; //allow use html in node name for highlight use
			
			var metaChar = '[\\[\\]\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)]'; //js meta characters
			var rexMeta = new RegExp(metaChar, 'gi');//regular expression to match meta characters
			
			// keywords filter function 
			function ztreeFilter(zTreeObj,_keywords,callBackFunc) {
				if(!_keywords){
					_keywords =''; //default blank for _keywords 
				}
				
				// function to find the matching node
				function filterFunc(node) {
					if(node && node.oldname && node.oldname.length>0){
						node[nameKey] = node.oldname; //recover oldname of the node if exist
					}
					zTreeObj.updateNode(node); //update node to for modifications take effect
					if (_keywords.length == 0) {
						//return true to show all nodes if the keyword is blank
						zTreeObj.showNode(node);
						zTreeObj.expandNode(node,isExpand);
						return true;
					}
					//transform node name and keywords to lowercase
					if (node[nameKey] && node[nameKey].toLowerCase().indexOf(_keywords.toLowerCase())!=-1) {
						if(isHighLight){ //highlight process
							//a new variable 'newKeywords' created to store the keywords information 
							//keep the parameter '_keywords' as initial and it will be used in next node
							//process the meta characters in _keywords thus the RegExp can be correctly used in str.replace
							var newKeywords = _keywords.replace(rexMeta,function(matchStr){
								//add escape character before meta characters
								return '\\' + matchStr;
							});
							node.oldname = node[nameKey]; //store the old name  
							var rexGlobal = new RegExp(newKeywords, 'gi');//'g' for global,'i' for ignore case
							//use replace(RegExp,replacement) since replace(/substr/g,replacement) cannot be used here
							node[nameKey] = node.oldname.replace(rexGlobal, function(originalText){
								//highlight the matching words in node name
								var highLightText =
									'<span style="color: whitesmoke;background-color: darkred;">'
									+ originalText
									+'</span>';
								return 	highLightText;					
							});
							zTreeObj.updateNode(node); //update node for modifications take effect
						}
						zTreeObj.showNode(node);//show node with matching keywords
						return true; //return true and show this node
					}
					
					zTreeObj.hideNode(node); // hide node that not matched
					return false; //return false for node not matched
				}
				
				var nodesShow = zTreeObj.getNodesByFilter(filterFunc); //get all nodes that would be shown
				processShowNodes(nodesShow, _keywords);//nodes should be reprocessed to show correctly
			}
			
			/**
			 * reprocess of nodes before showing
			 */
			function processShowNodes(nodesShow,_keywords){
				if(nodesShow && nodesShow.length>0){
					//process the ancient nodes if _keywords is not blank
					if(_keywords.length>0){ 
						$.each(nodesShow, function(n,obj){
							var pathOfOne = obj.getPath();//get all the ancient nodes including current node
							if(pathOfOne && pathOfOne.length>0){ 
								//i < pathOfOne.length-1 process every node in path except self
								for(var i=0;i<pathOfOne.length-1;i++){
									zTreeObj.showNode(pathOfOne[i]); //show node 
									zTreeObj.expandNode(pathOfOne[i],true); //expand node
								}
							}
						});	
					}else{ //show all nodes when _keywords is blank and expand the root nodes
						var rootNodes = zTreeObj.getNodesByParam('level','0');//get all root nodes
						$.each(rootNodes,function(n,obj){
							zTreeObj.expandNode(obj,true); //expand all root nodes
						});
					}
				}
			}
			
			//listen to change in input element
			$(searchField).bind('input propertychange', function() {
				var _keywords = $(this).val();
				searchNodeLazy(_keywords); //call lazy load
			});

			var timeoutId = null;
			var lastKeyword = '';
			// excute lazy load once after input change, the last pending task will be cancled  
			function searchNodeLazy(_keywords) {
				if (timeoutId) { 
					//clear pending task
					clearTimeout(timeoutId);
				}
				timeoutId = setTimeout(function() {
			if (lastKeyword === _keywords) {
				return;
			}
					ztreeFilter(zTreeObj,_keywords); //lazy load ztreeFilter function 
					// $(searchField).focus();//focus input field again after filtering
			lastKeyword = _keywords;
				}, 500);
			}
		}
    },
}




4.コンポーネント使用

treedata:バックグラウンドで返されるtreeデータフォーマット
"data":[
        {
            "catalogName":"   1",    //    
            "dataSourceGroupId":"111", //  ID
            "parentDSource":"NULL",    //  ID
            "type":"1"                 //     : 1-    0-  
        },
        {
            "catalogName":"  2",      //    
            "dataSourceGroupId":"rrr",  //  ID
            "parentDSource":"222",      //  ID
            "type":"0"                  //     : 1-    0-  
        },
    ],

addtype:ルートノードの表示非表示を追加する
addtreeNode:サブノードの表示非表示を追加する
zTreeBeforeRename:ノードコールバック関数の編集
 //     
        zTreeBeforeRename(obj) {
            this.nodeName=obj.treeNode.catalogName;
        },

zTreeOnClick:単一ノードコールバックをクリック
//       
        zTreeOnClick(obj) {
			if(obj.treeNode.type==1){
                //       
            }
            if(obj.treeNode.type==0){
                //      
            }
        },

addzTreeOne:ルートコールバックの追加
//      
        addzTreeOne() {
    
        },

shauxin:ツリー構造のリフレッシュ
//      
        shauxin() {
            //    tree  
        },

removeTreeNode:ノードの削除
//    
removeTreeNode(obj) {
    
}

追加と削除後にバックグラウンドインタフェースを直接呼び出してツリー構造をリフレッシュすると、ツリー構造の展開、選択などの操作が初期化されます.次のコードを使用してツリー構造を新規作成できます.
ノードの追加:
//        ....
   if(res.status == 200) { 
        //     
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var parentZNode = treeObj.getSelectedNodes(); //     
        var newNode = {
            catalogName: this.collectionName,//    
            dataSourceGroupId: res.data.id,//  id
            parentDSource: this.nodeid, //  id,            
            type: 1,  //     
            icon: icojq  //  
            iconOpen: files, //     
            iconClose: file, //     
        };
        newNode.nodeFlg = 1; //          
        newNode = treeObj.addNodes(parentZNode[0], newNode, true);
    }

ノードの編集:
//        ...
if(res.status == 200) {
    //    
     var zTree = $.fn.zTree.getZTreeObj("treeDemo");
     this.nodeobj.treeNode.catalogName = this.ruleForm.baseNodeName;
     zTree.updateNode(this.nodeobj.treeNode);
     this.conName = '';
 }

ノードを削除するには
//      ...
if(res.status == 200) {
    //    
    var treeObj = $.fn.zTree.getZTreeObj(obj.treeId);
    var parentZNode = treeObj.getNodesByParam("dataSourceGroupId", obj.treeNode.dataSourceGroupId, null);
    treeObj.removeNode(parentZNode[0]);
}

アイコンは、プロジェクトの画像の位置に応じて挿入されます.
import icojq from "@/assets/img/23.png"
import file from "@/assets/img/21.png"
import files from "@/assets/img/22.png"