Heim > Fragen und Antworten > Hauptteil
Ich versuche derzeit, Restful-Api-Aufrufe zu verwenden und Nachrichten zu verwenden, um das erzwungene Verspotten von d3.js durchzuführen. Das Problem ist, dass, wenn ich Daten von der API verwende und keine Daten vorhanden sind, der Mock aufgerufen wird, um damit umzugehen. Wenn ich auf den nächsten Tick warte this.$nextTick(simu)
所有位置最终都会成为 NaN
. Gibt es einen Grund für dieses Verhalten?
const URL = 'https://jsonplaceholder.typicode.com/posts'; new Vue({ el: '#app', data() { return { webGraph: { nodes: [], edges: [] }, graph1: { nodes:[ {url:2}, {url:3}, ], edges:[ {source:2, target:3}, ] } } }, created() { axios.get(URL).then((response) => { let node1 = { url: response.data[1].id } let node2 = { url: response.data[2].id } let edge = { source: {url:response.data[1].id}, target: {url:response.data[2].id} } this.webGraph.nodes.push(node1) this.webGraph.nodes.push(node2) this.webGraph.edges.push(edge) }) d3.forceSimulation(this.webGraph.nodes) .force("charge", d3.forceManyBody().strength(-25)) .force("link", d3.forceLink().id(d => d.url).links(this.webGraph.edges)) .on('end', function() { console.log("done") }); d3.forceSimulation(this.graph1.nodes) .force("charge", d3.forceManyBody().strength(-25)) .force("link", d3.forceLink().id(d => d.url).links(this.graph1.edges)) .on('end', function() { console.log("done") }); } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <h6>{{webGraph}}</h6> <br> <h6>{{graph1}}</h6> </div>
P粉2041364282024-03-22 10:24:59
webGraph
和 graphData1
之所以有不同的结果,是因为 webGraph
的模拟是在没有数据之前就开始的。如果您将 simulation
代码移到 axios.get().then
内部,那么您将看到它按您的预期工作。
const URL = 'https://jsonplaceholder.typicode.com/posts'; new Vue({ el: '#app', data() { return { webGraph: { nodes: [], edges: [] }, graph1: { nodes:[ {url:2}, {url:3}, ], edges:[ {source:2, target:3}, ] } } }, created() { axios.get(URL).then((response) => { let node1 = { url: response.data[1].id } let node2 = { url: response.data[2].id } let edge = { source: node1, target: node2 } this.webGraph = { nodes: [node1, node2], edges: [edge] }; d3.forceSimulation(this.webGraph.nodes) .force("charge", d3.forceManyBody().strength(-25)) .force("link", d3.forceLink().id(d => d.url).links(this.webGraph.edges)) .on('end', function() { console.log("done") }); }) d3.forceSimulation(this.graph1.nodes) .force("charge", d3.forceManyBody().strength(-25)) .force("link", d3.forceLink().id(d => d.url).links(this.graph1.edges)) .on('end', function() { console.log("done") }); } })
{{webGraph}}
{{graph1}}