import { defineComponent, ref, onMounted } from 'vue' import * as d3 from 'd3' export default defineComponent({ template: <svg ref="chartRef" style="width: 20px; height: 300px; background:red"></svg>, setup () { const chartRef = ref(null) // 创建ref引用 onMounted(() => { console.log(chartRef) const container = d3.select(chartRef.value) // 使用ref引用选择元素 const width = 50 // 设置标尺宽度 const height = 300 // 设置标尺高度 // 创建比例尺 const scale = d3.scaleLinear() .domain([0, 100]) // 数据范围 .range([height, 0]) // 图表高度范围 // 创建标尺图表 container.append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', `translate(${width / 2}, 0)`) // 设置标尺的位置 .call(d3.axisLeft(scale)) // 添加左侧的标尺刻度 }) return () => chartRef.value } }) 这段代码有什么问题呢
时间: 2024-02-24 22:58:38 浏览: 22
这段代码的问题在于,在 `container` 中已经选中了 `<svg>` 元素,但在接下来的代码中,又向其中添加了一个 `<svg>` 元素,这会导致出现嵌套的 `<svg>` 元素,而这是不被允许的。应该直接向选中的 `<svg>` 元素中添加 `<g>` 元素,并在 `<g>` 元素中绘制标尺。修改后的代码如下:
```
import { defineComponent, ref, onMounted } from 'vue'
import * as d3 from 'd3'
export default defineComponent({
template: '<svg ref="chartRef" style="width: 50px; height: 300px; background:red"></svg>',
setup () {
const chartRef = ref(null)
onMounted(() => {
const container = d3.select(chartRef.value)
const width = 50
const height = 300
const scale = d3.scaleLinear()
.domain([0, 100])
.range([height, 0])
const g = container.append('g') // 直接向container中添加<g>元素
.attr('transform', `translate(${width / 2}, 0)`)
.call(d3.axisLeft(scale))
})
return () => chartRef.value
}
})
```