G6策略树
//G6组件
<template>
<div id="container" :style="{ height: '500px', width: '100%' }" />
</template>
<script>
import G6 from '@antv/g6'
export default {
data() {
return {
contorlGraph: ''
}
},
methods: {
CheckChange(val) {
const container = document.getElementById('container')
const graph = new G6.TreeGraph({
container: 'container',
width: container.clientWidth,
height: container.clientHeight,
modes: {
default: [
{
type: 'collapse-expand',
onChange: function onChange(item, collapsed) {
const data = item.getModel()
data.collapsed = collapsed
return true
}
},
'drag-canvas',
'zoom-canvas'
]
},
defaultNode: {
size: 26,
anchorPoints: [
[0, 0.5],
[1, 0.5]
]
},
defaultEdge: {
type: 'cubic-horizontal'
},
nodeStateStyles: {
// hover 状态为 true 时的样式 hover: {
fill: '#4d78cc'
}
},
layout: {
type: 'compactBox',
direction: 'LR',
getId: function getId(d) {
return d.id
},
getHeight: function getHeight() {
return 16
},
getWidth: function getWidth() {
return 16
},
getVGap: function getVGap() {
return 10
},
getHGap: function getHGap() {
return 100
}
}
})
graph.node(function (node) {
return {
label: node.data.label,
labelCfg: {
offset: 10,
position: node.children && node.children.length > 0 ? 'left' : 'right',
style: {
fill:
node.depth === 3
? node.status
? '#6b9bfa'
: '#000000'
: '#6b9bfa'
}
}
}
})
// 闪开功能
// G6.Util.traverseTree(val, function (item) {
// if (item.data.hasChild === true) {
// item.collapsed = true
// }
// })
graph.on('node:click', (ev) => {
const { item } = ev
// console.log(item)
if (item._cfg.model.data.response) {
graph.setItemState(item, 'hover', true)
this.$emit('treeDataResponse', item._cfg.model.data)
return {
style: {
fill: '#00a23c',
stroke: '#ea7171'
}
}
}
})
// 监听鼠标离开节点
graph.on('node:mouseleave', (ev) => {
const { item } = ev
// 设置目标节点的 hover 状态 false
setTimeout(() => {
graph.setItemState(item, 'hover', false)
}, 500)
})
this.contorlGraph = graph
graph.data(val)
graph.render()
graph.fitView()
},
handleCheckChange(val) {
// 如果画布没有渲染节点的情况
if (!this.contorlGraph.cfg) {
this.CheckChange(val)
this.destroyDrag()
this.CheckChange(val)
} else {
// 有渲染节点,再次点击到有节点的数据,避免重复渲染
this.destroyDrag()
setTimeout(() => { this.CheckChange(val) }, 20)
}
},
// 销毁画布 destroyDrag() {
// 如果画布已经被销毁,则不再执行
if (this.contorlGraph.cfg != null || this.controlGraph.cfg != undefined) {
this.contorlGraph.destroy()
} else {
return false
}
}
}
}</script>
<style lang="scss" scoped>
#container {
margin-left: 75px;
width: 100%;
height: 100%;
border: 1px solid #eee;
}</style>
使用组件
//引入组件
<dataTreeref="TREE_DATA"@treeDataResponse="treeDataResponse" />
//给组件传值
this.$refs.TREE_DATA.handleCheckChange(res.data)
//获取选中节点的值
treeDataResponse(val) {
// 获取节点名称
console.log(val);
this.$forceUpdate()
},
效果图
本文来自博客园,作者:云霄紫潭,转载请注明原文链接:https://www.cnblogs.com/0520euv/p/14821847.html