Vue 使用 AntV x6报错: “Error: Ensure the container of the graph is specified and valid“
今天在工作中,使用了 AntV 旗下的图编辑引擎 X6 来实现功能。该组件库提供了一系列开箱即用的交互组件和简单易用的定点节制能力,方便我们快速搭建流程图、DAG 图、ER 图等。但是在使用时,遇到了Error: Ensure the container of the graph is specified and valid 报错问题:对这个错误进行分析可以发现,错误原因是在 mounted 生命
今天在工作中,使用了 AntV 旗下的图编辑引擎 X6 来实现功能。该组件库提供了一系列开箱即用的交互组件和简单易用的定点节制能力,方便我们快速搭建流程图、DAG 图、ER 图等。但是在使用时,遇到了Error: Ensure the container of the graph is specified and valid 报错问题:
对这个错误进行分析可以发现,错误原因是在 mounted 生命周期时,id 为 container 的 div 还没有被挂载到页面中。这就导致我们想要将 graph 绘制在 id 为 container 的 div 上时,该节点还不存在,也就导致了报错。
由于这方面的资料少之又少,通过其他博文可以知道,在修改调用该方法的生命周期就解决了问题,但是在我的功能模块中,即使修改了生命周期,问题也依然没能解决(没能解决的原因,个人猜测可能是因为,我的这个 div 放在了 ElementUI 的组件 el-dialog 上,从而导致该 div 没能加载出来)。经过测试发现,只有在页面经历过一次生命周期后,这个 div 节点才能挂载到页面上。为了解决这个问题,在代码中添加了定时器,只有在这个 div 加载出来之后,再去绘制 graph:
(相关代码:)
<template>
<div class="opticalFiber">
<el-dialog
title="测试"
:visible.sync="visible"
:before-close="cancel"
width="80%"
center
>
<el-form :model="form" ref="form" label-width="120px" :rules="rules">
<el-row>
...
</el-row>
<div id="container"></div>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="submit">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { Graph } from "@antv/x6";
export default {
data() {
return {
...
data: {
// 节点
nodes: [
{
id: 'node1', // String,可选,节点的唯一标识
x: 40, // Number,必选,节点位置的 x 值
y: 40, // Number,必选,节点位置的 y 值
width: 80, // Number,可选,节点大小的 width 值
height: 40, // Number,可选,节点大小的 height 值
label: 'hello', // String,节点标签
},
{
id: 'node2', // String,节点的唯一标识
x: 160, // Number,必选,节点位置的 x 值
y: 180, // Number,必选,节点位置的 y 值
width: 80, // Number,可选,节点大小的 width 值
height: 40, // Number,可选,节点大小的 height 值
label: 'world', // String,节点标签
},
],
// 边
edges: [
{
source: 'node1', // String,必须,起始节点 id
target: 'node2', // String,必须,目标节点 id
},
],
}
};
},
methods: {
initGraph(){
// 确保 id 为 container 的 div 存在
if(document.getElementById('container') === null){
const judgeGraphDiv = setInterval(()=>{
if(document.getElementById('container') !== null){
window.clearInterval(judgeGraphDiv);
this.drawGraph();
}
},1000)
} else {
this.drawGraph();
}
},
drawGraph(){
const graph = new Graph({
container: document.getElementById('container'),
width: 800,
height: 300,
interacting: {
nodeMovable: false
}
});
graph.fromJSON(this.data);
},
....
},
watch: {
visible(val) {
// 每次进入弹框时进行判定
val && this.initGraph();
}
}
}
</script>
<style scoped lang="scss">
...
</style>
更多推荐
所有评论(0)