我有 App.vue
:
<template>
<div>
<p class="text">Hello World</p>
</div>
</template>
<script>
import ParentComponent from '../components/ParentComponent'
export default {
components: {
ParentComponent
}
}
</script>
然后我有 ParentComponent
:
<template>
<div>
<p class="text">Hello World</p>
<ChildComponent />
</div>
</template>
<script>
import ChildComponent from '../ChildComponent'
export default {
components: {
ChildComponent
}
}
</script>
<style>
.text {
font-size: 30px
}
</style>
子组件
:
<template>
<p class="text">Hello World</p>
</template>
<script>
export default {
}
</script>
<style>
</style>
现在,无论我在 ParentComponent
中有什么样式,我都希望子组件也具有该样式。
但是,我不希望 App.vue
有那种风格。此外,如果 ChildComponent
有任何其他组件,那么它们也应该继承 ParentComponent
的样式。就像 ParentComponent
是样式提供者。
我真的没有任何代码可以展示。我只想知道这是否可能以及如何实现?
最佳答案
您可以简单地在父组件中使用您希望子组件使用的样式创建一个 css 类。然后您只需在 child 中使用该类。
只要子组件确实作为子组件嵌套在父组件中,您的示例实际上就按照您希望的方式工作。
我们在公司所做的是,我们总是用一个与组件名称同名的类来包装组件。如果您正在做一些奇怪的父类型样式,这会让您的样式变得非常明显。
父组件:
<template>
<div>
<p class="text">Hello World</p>
<ChildComponent />
</div>
</template>
<script>
import ChildComponent from '../ChildComponent'
export default {
components: {
ChildComponent
}
}
</script>
<style>
.some-class-name {
/*...*/
}
.text {
font-size: 30px
}
</style>
子组件:
<template>
<div class="some-class-name">
<p class="text">Hello World</p>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
关于javascript - 有没有办法将父 css 泄漏到 Vue 中的子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57657341/