// 定义数据源
const data = {
// 点集
nodes: [
{
id: 'node1',
x: 100,
y: 200,
},
{
id: 'node2',
x: 300,
y: 200,
},
],
// 边集
edges: [
// 表示一条从 node1 节点连接到 node2 节点的边
{
source: 'node1',
target: 'node2',
},
],
};
function initG6(){
const container = document.getElementById('container');
const width = container.scrollWith || 500;
const height = container.scrollHeight || 500;
// 创建 G6 图实例
const graph = new G6.Graph({
container: 'mountNode', // 指定图画布的容器 id
// 画布宽高
width,
height,
});
// 读取数据
graph.data(data);
// 渲染图
graph.render();
}
onMounted(()=>{
initG6();
});
<div id="mountNode" />
这样的话,conatiner.scrollWith 代码返回的是0
conatiner.scrollWith ==> 0
原因是DOM元素还没有被完全渲染出来。Vue的生命周期钩子可以帮助你确保在正确的时间点获取元素的宽度。
import {
ref,
computed,
unref,
onMounted,
nextTick,
} from 'vue';
onMounted(()=>{
nextTick(() => {
initG6();
});
});
外面只要包裹一个nextTick就可以。