在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阶段打印出的数据和在页面渲染出的数据为什么会不一样呢?**
页面渲染出的数据: