vue 中应用 ztree
应用步骤如下
npm install @ztree/ztree_v3
- ztree 依赖 jquery,下载 jquery
npm install jquery
所以须要在 vue.config.js 中配置 jquery
plugins: [
new webpack.ProvidePlugin({
$:"jquery",
jQuery:"jquery",
"windows.jQuery":"jquery"
})
],
3. 在 main.js 中援用
import '@ztree/ztree_v3/js/jquery.ztree.core.min.js'
import '@ztree/ztree_v3/js/jquery.ztree.excheck.min.js'
// import '@ztree/ztree_v3/css/zTreeStyle/zTreeStyle.css'(ztree 另一种款式)
import '@ztree/ztree_v3/css/metroStyle/metroStyle.css'
4. 封装 ztree 组件
<template>
<div class="treeBox">
<div>
<ul :id="id" class="ztree"></ul>
</div>
</div>
</template>
<script>
export default {
name: "ZTree",
props: {
zNodes: {// 树结构数据
type: Array,
default () {return [];
}
},
id:{
type: String,
default () {return 'treeDemo';}
},
isShowBtn_modify:{
type: Boolean,
default:false
},
isShowBtn_delete:{
type: Boolean,
default:false
}
},
data() {
return {
setting:{ // 树形构造设置参数
data:{
key: {name: "name"},
simpleData:{
enable: true,
idKey: "deptId",
pIdKey: "parentId",
rootPId: 0
}
},
view: {showLine: false// 连接线},
edit: {// 是否能够删除编辑
enable: true,
showRemoveBtn: this.isShowBtn_modify,
removeTitle: "删除",
showRenameBtn: this.isShowBtn_delete,
renameTitle: "编辑"
},
callback: {
onClick: this.onNodeClick,
beforeEditName: this.beforeEditName,// 批改节点之前
beforeRemove:this.beforeRemove// 删除节点之前
}
}
}
},
mounted(){this.init();
},
methods:{
// 初始化 ztree
init() {if (!this.zNodes) {return}
$.fn.zTree.init($("#"+this.id), this.setting, this.zNodes);
},
// 单击选中目录
onNodeClick(e, treeId, treeNode) {this.$emit('getTreeNode',treeNode);
console.log(treeNode);
},
// 批改节点之前
beforeEditName(treeId, treeNode){
// 发射给父组件信息
this.$emit('zTreeBeforeReName',treeNode.deptId);
return false
// return !treeNode.isParent;
},
// 删除节点之前
beforeRemove(treeId, treeNode) {this.$emit('zTreeBeforeRemove',treeNode.deptId);
console.log('删除节点之前',treeNode.deptId);
return false;
},
// 开展某节点
expandMode(pid){$.fn.zTree.init($("#"+this.id), this.setting, this.zNodes);
let zTree_Menu = $.fn.zTree.getZTreeObj(this.id);
let node = zTree_Menu.getNodeByParam("deptId",pid);
zTree_Menu.selectNode(node,true);// 指定选中 ID 的节点
zTree_Menu.expandNode(node, true, false);// 指定选中 ID 节点开展
}
}
}
</script>
5. 父组件中援用,记得引入与注册
// 页面应用
<Ztree :zNodes="pageList" id="modelTree" @getTreeNode="getTreeNode_depart" ref="modelTree" :key="componentKey"></Ztree>
// 引入
import Ztree from '@/components/common/ZTree.vue'
//data 中应用
componentKey:0,
// 强制刷新一下树结构,从新渲染, 每次加载数据后须要 `this.componentKey++`,不然渲染不进去
// 注册组件
components:{Ztree},
6. 子组件中的办法,父组件随便援用,例子如下
// 刷新树结构办法
refreshTreeMethod(){this.$refs.pageTree.init();// 刷新树结构 - 页面树
this.componentKey++;
},
齐活~~