问题描述
保存一下,我有一个 .Vue
组件,该组件是我从Github上获取的。让我们将其称为CompB,然后在其中为蓝色标头添加一个CSS规则集:
Let's save I have a .Vue
component that I grab off of Github somewhere. Let's call it CompB and we'll add a single CSS rule-set there for a blue header:
CompB.Vue (依赖项I不拥有,也许是从Github撤出的。)
CompB.Vue (a dependency I don't own, perhaps pulled from Github)
<template>
...
</template>
<script>
...
</script>
<style lang="scss" scoped>
.compb-header {
color: blue;
}
</style>
我计划将CompB嵌套到我自己项目的CompA中。现在,我有什么方法可以覆盖作用域规则?
I plan to nest CompB into my own project's CompA. Now what are my options for overriding the scoped rule?
推荐答案
经过一段时间的尝试,我认为我有一个不错的选择
After playing around a bit, I think I've got a good approach.
-
全局替代
Global overrides
对于我想使用的情况在所有情况下都覆盖CompB的规则我可以添加一个更具体的规则集,例如: #app .compb-header {..}
。由于我们始终只有一个根( #app
),因此在规则集中使用ID是安全的。这很容易覆盖CompB中的范围规则。
For situations where I want to override the rules in all cases for CompB I can add a rule-set with more specificity like this: #app .compb-header { .. }
. Since we always only have one root (#app
) it's safe to use an ID in the rule-set. This easily overrides the scoped rules in CompB.
父级覆盖
对于我想要的情况覆盖全局规则和范围规则。幸运的是,VueJS允许将范围和非范围的样式块添加到.Vue文件中。因此,我可以添加一个更具体的CSS规则集。还要注意,因为Vue为所有组件提供了内置的类和样式道具,所以我可以将类传递给CompB的道具:
For situations where I want to override both the global and scoped rules. Thankfully VueJS allows adding both a scoped and unscoped style block into a .Vue file. So I can add an even more specific CSS rule-set. Also notice I can pass a class into CompB's props since Vue provides built-in class and style props for all components:
// in CompA (the parent)
<template>
...
<!-- Vue provides built-in class and style props for all comps -->
<compb class="compb"></compb>
</template>
<script>
...
</script>
<style lang="scss">
#app .compb .compb-header {
color: red;
}
</style>
<style lang="scss" scoped>
...
</style>
(注意:您可以更具体一些,使传递到CompB的类具有一个更独特的名称,例如 .compa-compb
或某些哈希后缀,因此不会与使用CompB和类 .compb的其他组件发生冲突。
。但是我认为这对于大多数应用程序来说可能是过大的了。)
(note: You can get more specific and make the class you pass into CompB have a more unique name such as .compa-compb
or some hash suffix so there is no potential for collision with other components that use CompB and a class .compb
. But I think that might be overkill for most applications.)
用于调整CSS或将类/样式传递到组件区域的其他道具。但是,当您使用自己不拥有的组件时,情况可能并非总是如此(除非您分叉它)。另外,即使提供了此功能,也总是存在一些情况,例如我只想稍微调整一下填充!。以上两种解决方案似乎对此非常有用。
And of course CompB may provide its own additional props for adjusting CSS or passing classes/styles into areas of the component. But this may not always be the case when you use a component you don't own (unless you fork it). Plus, even with this provided, there is always those situations where you are like "I just want to adjust that padding just a bit!". The above two solutions seem to work great for this.
这篇关于如何覆盖Vue组件中的作用域样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!