以数
npm install x6-hooks
yarn add x6-hooks
import { useGraphState } from 'x6-hooks/react'
const { nodes, setNodes, edges, setEdges, graph, setGraph } = useGraphState()
// setNodes and setEdges return Promise
useEffect(() => {
const graph = new X6.Graph({ ... })
setGraph(graph)
// init data
setNodes([...])
setEdges([...])
}, [])
const addNode = useCallback((node: Node.Metadata) => {
// add node to nodes array
setNodes([...nodes, node])
}, [nodes])
const addEdge = useCallback((edge: Edge.Metadata) => {
setEdges([...edges, edge])
}, [edges])
const updateNode = useCallback((nodeId: string, node: Node.Metadata) => {
const index = nodes.findIndex(node => node.id === nodeId)
if (index > -1) {
nodes[index] = node
setNodes([...nodes])
}
}, [nodes])
const updateEdge = useCallback((edgeId: string, edge: Edge.Metadata) => {
const index = edges.findIndex(edge => edge.id === edgeId)
if (index > -1) {
edges[index] = edge
setEdges([...edges])
}
}, [edges])
const removeNode = useCallback((nodeId) => {
setNodes(nodes.filter(node => node.id !== nodeId))
// remove related edges
setEdges(edges.filter(edge => {
if (edge.source === nodeId || edge.source.cell === nodeId) {
return false
}
if (edge.target === nodeId || edge.target.cell === nodeId) {
return false
}
return true
})
}, [nodes, edges])
const removeEdge = useCallback((edgeId) => {
setEdges(edges.filter(edge => edge.id !== edgeId))
}, [edges])
import { useGraphState } from 'x6-hooks/vue'
const { nodes, edges, graph, setNodes, setEdges, setGraph } = useGraphState()
// setNodes and setEdges return Promise
onMounted(() => {
const graph = new X6.Graph({ ... })
setGraph(graph)
// init data
setNodes([...])
setEdges([...])
})
const addNode = (node: Node.Metadata) => {
// add node to nodes array
setNodes([
...nodes.value, // nodes is ref
node,
])
}
const addEdge = (edge: Edge.Metadata) => {
setEdges([
...edges.value, // edges is ref
edge,
])
}
const updateNode = (nodeId: string, node: Node.Metadata) => {
const index = nodes.value.findIndex(node => node.id === nodeId)
if (index > -1) {
nodes.value[index] = node
setNodes([...nodes.value])
}
}
const updateEdge = (edgeId: string, edge: Edge.Metadata) => {
const index = edges.value.findIndex(edge => edge.id === edgeId)
if (index > -1) {
edges.value[index] = edge
setEdges([...edges.value])
}
}
const removeNode = (nodeId) => {
setNodes(nodes.value.filter(node => node.id !== nodeId))
// remove related edges
setEdges(edges.value.filter(edge => {
if (edge.source === nodeId || edge.source.cell === nodeId) {
return false
}
if (edge.target === nodeId || edge.target.cell === nodeId) {
return false
}
return true
})
}
const removeEdge = (edgeId) => {
setEdges(edges.value.filter(edge => edge.id !== edgeId))
}
使用 x6-hooks管理 数 据 使用 x6-graph封 装 图实例 - x6-graph
子 组件的 模 式 对业务逻辑做拆分组合(也可以用这个模 式 抽象 一些常用的组件,例 如将官 方 的 plugin抽象 成 UI组件挂载到Graph内部 )