报错信息:代码展示:
<!--
* @Author: zhangdapan
* @Date: 2023-11-01 10:01:49
* @LastEditors: Please set LastEditors
* @LastEditTime: 2023-11-01 10:38:56
* @Description: antv x6思维导图封装
-->
<template>
<div id="container"></div>
</template>
<script>
import { Graph } from '@antv/x6';
// antv x6 思维导图
export default {
name: 'antv-x',
props: {
graphData:{
type: Object,
default: this.graphDataObj
}
},
data() {
return {
graphDataObj: {
nodes: [
{
id: 'node1',
shape: 'rect', // 使用 rect 渲染
x: 100,
y: 200,
width: 80,
height: 40,
label: 'hello',
},
{
id: 'node2',
shape: 'ellipse', // 使用 ellipse 渲染
x: 300,
y: 200,
width: 80,
height: 40,
label: 'world',
},
],
edges: [
{
source: 'node1',
target: 'node2',
},
],
}
}
},
mounted() {
setTimeout(() => {
this.getInit()
}, 0);
},
methods: {
getInit() {
const graph = new Graph({
container: document.getElementById('container'),
width: 500,
height: 500,
background: {
color: '#fffbe6', // 设置画布背景颜色
},
});
graph.fromJSON(this.graphData)
}
}
}
</script>
<style>
</style>
问题出现在访问 graphDataObj
属性时,它被认为是未定义的。
这个问题的原因是在 props
中的 default
属性中,使用了 this.graphDataObj
,但是在那个时候 graphDataObj
还没有被定义,所以它是 undefined
。
为了解决这个问题,可以将 default
属性的值设置为一个函数,然后在函数中返回默认的 graphDataObj
对象。这样可以确保在默认情况下,graphDataObj
被正确地定义和返回。
修改后代码:
props: {
graphData:{
type: Object,
default() {
return {
nodes: [
{
id: 'node1',
shape: 'rect', // 使用 rect 渲染
x: 100,
y: 200,
width: 80,
height: 40,
label: 'hello',
},
{
id: 'node2',
shape: 'ellipse', // 使用 ellipse 渲染
x: 300,
y: 200,
width: 80,
height: 40,
label: 'world',
},
],
edges: [
{
source: 'node1',
target: 'node2',
},
],
}
}
}
},