前篇:vue3+ts使用antv/x6 + 自定义节点
前篇:vue3+antv x6自定义节点样式
1、创建侧边栏
- 用antd的menu来做侧边栏
sql
npm i --save ant-design-vue@4.x
js
//入口文件main.js内
import Antd from 'ant-design-vue';
import App from './App';
import 'ant-design-vue/dist/reset.css';
const app = createApp(App);
app.use(Antd).mount('#app');
- 侧边栏结构
json
// index.js内,拖拽节点侧边栏
export const MENU_TREE = [
{
key: '1',
label: 'type1',
title: 'drag node 1',
},
]
- 画布展示
js
//index.vue内
<template>
<div class="box">
<a-menu
class="menutree"
:items="menutree"
/>
<div id="container"></div>
</div>
<TeleportContainer/>
</template>
<script setup lang='ts'>
import {MENU_TREE} from "./index";
let menutree = MENU_TREE
</script>
<style scoped>
.menutree{
display: flex;
position: relative;
}
#container{
height: 100vh;
}
.menutree{
width: 200px;
height: 100vh;
position: absolute;
left: 0;
top: 0;
flex-direction: column;
z-index: 2;
user-select: none;/* 鼠标按下时没有复制等操作 */
}
</style>
2、拖拽交互
- 安装
sql
npm install @antv/x6-plugin-dnd --save
- 引入并使用(index.vue)
js
import { Dnd } from '@antv/x6-plugin-dnd'
//...
let dnd:Dnd
//开始拖拽
const startDrag = (e,nodevo)=>{
const node = graph.createNode(formatData(nodevo))
dnd.start(node, e)
}
//初始化画布
const graphInit = ()=>{
//...
dnd = new Dnd({
target: graph,
getDragNode: (node) => node.clone({ keepId: true }),//拖拽开始时,获取被拖拽的节点,默认克隆 dnd.start 传入的节点。
getDropNode: (node) => {//拖拽结束时,获取放置到目标画布的节点,默认克隆被拖拽的节点。
return graph.createNode(formatData(node.getData()))
}
})
}
3、侧边栏和拖拽建立联系
- 在侧边栏menu中添加拖拽节点信息(index.js)
json
MENU_TREE = [{
key: '1',
label: 'type1',
title: 'drag node 1',
ports:[{
id: 'port-1',
name: 'drag1-port1',
}]
}]
- fomatMenu处理menu内需要拖拽到节点信息(index.js)
js
export function fomatMenu (menu: any, dragStart) {
let tempmenu = menu.map(ele => {
const nodeVO = {
id: `node-${Math.random()}`,
nodeName: ele.title,
x: 0,
y: 0,
ports: ele.ports
}
return {
key: ele.key,
label: ele.label,
onMousedown: (e: Event) => {
dragStart(e, nodeVO)
},
}
});
return tempmenu
}
- 主画布渲染menu时先处理menu信息
js
import {MENU_TREE,fomatMenu} from "./index";
let menutree = fomatMenu(MENU_TREE,startDrag) //放在startDrag之后
- 效果