使用Vue+d3做知识图谱,无法使用d3-force处理后的数据
在vue中使用v-for循环,让svg标签的属性使用d3处理后的数据,但是在html中渲染的数据和d3.forceSimulation处理后的数据不一样,在mounted阶段打印出的数据和在页面渲染出的数据为什么会不一样呢?
源代码:
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript" src="http://d3js.org/d3.v5.min.js"> </script>
</head>
<body>
<div id='app'>
<p v-for="(path,i) in edges" :key="i">
{{path.source}}
</p>
<svg :width="width" :height="height">
<line v-for="(path,i) in edges" :key="i"
:x1="path.source.x"
:y1="path.source.y"
:x2="path.target.x"
:y2="path.target.y"
style="stroke:rgb(66,66,66);stroke-width:2"
/>
<circle v-for="(node,i) in nodes"
:key="(i+1)*10"
:cx="node.x"
:cy="node.y"
:r="10"
fill="red"
/>
</svg>
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
width: 960,
height: 500,
realnodes: [],
realedges: [],
nodes: [
{ name: "湖南邵阳" },
{ name: "山东莱州" },
{ name: "广东阳江" },
{ name: "山东枣庄" },
{ name: "泽" },
{ name: "恒" },
{ name: "鑫" },
{ name: "明山" },
{ name: "班长" }
],
edges: [
{ source: 0, target: 4, relation: "籍贯", value: 1.8 },
{ source: 4, target: 5, relation: "舍友", value: 1 },
{ source: 4, target: 6, relation: "舍友", value: 1 },
{ source: 4, target: 7, relation: "舍友", value: 1 },
{ source: 1, target: 6, relation: "籍贯", value: 2 },
{ source: 2, target: 5, relation: "籍贯", value: 0.9 },
{ source: 3, target: 7, relation: "籍贯", value: 1 },
{ source: 5, target: 6, relation: "同学", value: 1.6 },
{ source: 6, target: 7, relation: "朋友", value: 0.7 },
{ source: 6, target: 8, relation: "职责", value: 2 }
]
},
created() {
},
mounted() {
this.initData()
console.log("before mount")
console.log(this.nodes)
console.log(this.edges)
},
methods: {
initData() {
var forceSimulation = d3.forceSimulation()
.force("link", d3.forceLink())
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter())
.force('collision', d3.forceCollide(25));
forceSimulation.nodes(this.nodes)
// console.log(this.nodes)
forceSimulation.force("link")
.links(this.edges)
// .id((d) => {
// return nodes.name
// })
.distance(function (d) {
return d.value * 150;
})
this.realnodes = this.nodes
this.realedges = this.edges
forceSimulation.force("center")
.x(this.width / 2)
.y(this.height / 2);
}
}
})
</script>
</body>
</html>`
**
在mounted阶段打印出的数据和在页面渲染出的数据为什么会不一样呢?**
页面渲染出的数据:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论