【发布时间】:2019-01-28 18:17:44
【问题描述】:
我正在尝试集成 Vue.js 和 D3.js。我注意到有时 CSS 类并不真正适用于 svg 元素。下面我给出vue组件的sn-p。
<template>
<div>
<h1>Hello world</h1>
<svg width="300" height="100" ref="barchart"></svg>
</div>
</template>
<script>
import * as d3 from "d3";
export default {
name: "LineChart",
mounted() {
d3.select("h1").attr("class","red-text")
var data = [10,20,15,30,60];
var barHeight = 20;
var bar = d3
.select(this.$refs.barchart)
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("class","rect")
.attr("width", function(d) {
return d;
})
.attr("height", barHeight - 1)
.attr("transform", function(d, i) {
return "translate(0," + i * barHeight + ")";
});
}
};
</script>
<style scoped>
.rect{
fill: blue;
}
.red-text{
color:red;
}
</style>
其输出为:-
但是当我删除 scoped 属性时,代码可以正常工作。新输出:-
提前致谢!
【问题讨论】:
-
也许指定 vue 的深层子选择器会起作用?例如
svg >>> .rect { ... }. -
@CoderinoJavarino 它正在工作!但这被认为是一种好的做法吗?
-
你的 svg 选择器仍然有作用域,所以样式不应该泄漏到组件之外。我认为这没有任何缺点。