我正在開發Vue 3應用程式,我想使用一個組件的多個實體。每個組件都應該有自己的D3實體來顯示各種SVG圖片。在我的案例中,D3只在Vue組件的第一個實體上按計劃作業。
點是由D3隨機生成的。在檢查元素時,我可以看到在組件的第二個實體中,沒有任何一個點被添加。這個問題的截圖可以在這里找到。
我的D3組件是這樣的:
<template>
<div class="fill-100"/span>>
< svg ref="svgRef"/span> width="400" height=667>
<g></g>
</svg>/span>
</div>/span>
</template>
<script>。
import {ref, onMounted} from "@vue/runtime-core" 。
import {select, zoom}. from "d3";
export default {
name: "SldSvgD3"/span>,
props: ["id"]。
setup(){
const svgRef = ref(null)。
onMounted(() =>/span>{
const svg = select(svgRef.value)。
svg.append("svg"/span>)
let data = [], width = 400, height = 667, numPoints = 100;
let zoom3 = zoom()
.on('zoom', handleZoom)。
function handleZoom(e){
select('svg g')
.attr('transform', e.transform) 。
}
function initZoom() {
select('svg')
.call(zoom3)。
}
function updateData() {
data = [];
for(let i=0; i< numPoints; i ) {
data.push({
id: i,
x: Math.random() * width,
y: Math.random() * height
});
}
}
function update() {
select('svg g')
.selectAll('圓')
.data(data)
.join('circle')
.attr('cx', function(d) { return d。 x; })
.attr('cy', function(d) { returnd. y; })
.attr('r', 3) 。
}
initZoom()。
updateData()。
update()。
});
return {svgRef}.
}
}
</script>>
<style lang="scss">/span>
.fill-100{
width: 100%。
height: 100%。
}
</style>>
D3縮放和平移的實施取自這個網站
uj5u.com熱心網友回復:
我不知道的是,d3.select()呼叫的范圍對整個應用程式是全域的。在我的案例中,解決方案只是為根div創建唯一的id,并在任何操作之前選擇這個div。
這個問題對我很有幫助。
完整的代碼:
<template>
<div class="fill-100" : id="'sld_div' this. id">
</div>/span>
</template>
<script>。
import {ref, onMounted} from "@vue/runtime-core" 。
import * as d3 from "d3"/span>;
export default {
name: "SldSvgD3"/span>,
props: ["id"]。
setup(props){
const svgRef = ref(null)。
const svg_width = 400;
const svg_height = 667;
onMounted(() =>/span>{
const svg = d3
.select("#sld_div"/span> props.id)
svg.append("svg"/span>)
.attr("id","sld_root" props.id)
.attr("width", svg_width)
.attr("height", svg_height)
.append("g")
.attr("id","sld_root_g" props.id)
let data = [], width = 600, height = 400, numPoints = 100;
let zoom = d3.zoom()
.on('zoom', handleZoom)。
function handleZoom(e){
d3.select("#sld_div"/span> props.id)
.select('svg g')
.attr('transform', e.transform) 。
}
function initZoom() {
d3.select("#sld_div"/span> props.id)
.select('svg')
.call(zoom)。
}
function updateData() {
data = [];
for(let i=0; i< numPoints; i ) {
data.push({
id: i,
x: Math.random() * width,
y: Math.random() * height
});
}
}
function update(){
d3.select("#sld_div"/span> props.id)
.select('svg g')
.selectAll('圓')
.data(data)
.join('circle')
.attr('cx', function(d) { return d。 x; })
.attr('cy', function(d) { returnd. y; })
.attr('r', 3) 。
}
initZoom()。
updateData()。
update()。
});
return {svgRef}.
}
}
</script>>
<style lang="scss">/span>
.fill-100{
width: 100%。
height: 100%。
}
</style>>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331508.html
標籤:
