[英]How to pass styles to child component and use it as scoped style in Vue?
我有一個父組件:
<template>
<ChildComponent :styles="styles" />
</template>
<script>
export default {
data: () => ({
styles: `
p {
color: red
}
`
})
}
</script>
這是子組件:
<template>
<p>Hello World</p>
</template>
<script>
export default {
props: {
styles: {
type: String,
required: true
}
}
}
</script>
<style scoped>
</style>
現在我想使用父組件在子組件中提供的那些 styles 作為范圍 styles。例如:
<!-- ChildComponent.vue -->
<style scoped>
p {
color: red
}
</style>
有什么辦法嗎?
如果要使用范圍樣式定位子元素,則必須使用深度選擇器。
可以用
a >>> b { color : red; }
/deep/ a b { color : red; }
a::v-deep b { color : red; }
這是完整的解釋: https : //vue-loader.vuejs.org/guide/scoped-css.html#child-component-root-elements
我有一個父組件:
<template>
<ChildComponent :styles="styles" />
</template>
<script>
export default {
data: () => ({
styles: `
p {
color: red
}
`
})
}
</script>
這是子組件:
<template>
<p>Hello World</p>
</template>
<script>
export default {
props: {
styles: {
type: String,
required: true
}
}
}
</script>
<style scoped>
</style>
現在,我想使用父級組件在子級中提供的那些樣式作為范圍樣式。 例如:
<!-- ChildComponent.vue -->
<style scoped>
p {
color: red
}
</style>
有什么辦法嗎?
如果你想在你的子組件中添加樣式,基於調用它的父組件,你可以將一個屬性作為 prop 傳遞並將它作為一個類使用到子組件中。 按照你的例子:
父組件:
<template>
<ChildComponent styles="parent-style" />
</template>
子組件:
<template>
<section :class="styles">
<p>Hello World</p>
</section>
</template>
<script>
export default {
props: {
styles: {
type: String,
required: true
}
}
}
</script>
<style lang="scss" scoped>
.parent-style {
p {
color: red;
}
}
</style>
請注意,它不回答范圍為 CSS 的問題。我正在使用CSS 模塊,仍然可能有所幫助或只是為了改進以下方法。
從父組件向子組件發送 class 名稱,例如:
父模板
<template>
<header :class="$style.Header">
<!-- send class names to **Child-Component** using `v-bind` through the className attribute -->
<HeaderLogo :className="$style.Header__logo" />
</header>
</template>
子模板
<template>
<div :class="className">Blah</div>
</template>
CSS 模塊
<style lang="scss" module>
.Header {
white-space: nowrap;
&__logo {
width: 100%;
}
}
</style>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.