【问题标题】:How to pass styles to child component and use it as scoped style in Vue?如何将样式传递给子组件并将其用作 Vue 中的作用域样式?
【发布时间】:2020-01-02 09:11:32
【问题描述】:

我有一个父组件:

<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>

有什么办法吗?

【问题讨论】:

  • 您可以将您的样式作为道具传递,然后获取样式对象并将其用于您的模板。 &lt;div v-bind:style="{...styles }"&gt;&lt;/div&gt; 更多信息可以在这里找到:vuejs.org/v2/guide/class-and-style.html

标签: javascript css vue.js vue-component


【解决方案1】:

如果您想使用作用域样式定位子元素,您必须使用深度选择器。

这可以用

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

【讨论】:

  • /deep/ 也可以工作 bambielli.com/til/…
  • 应该是/deep/ 而不是\deep\ 我更正了帖子
  • 我在使用/deep/时得到expected selector编译错误
【解决方案2】:

如果你想在你的子组件中添加样式,基于调用它的父组件,你可以将一个属性作为一个 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>

【讨论】:

  • 这仅适用于您可以访问子源的情况。我认为更有可能的情况是您需要将作用域样式传递给您无法访问其来源的孩子。
  • 添加到 Jamie,另一种情况是您有一个包装器,其中每个孩子都将使用相同的样式,因此您希望在包装器(父级)上应用一次样式而不是每个孩子,例如: 标题、文字设计、按钮等
猜你喜欢
  • 1970-01-01
  • 2019-11-03
  • 2021-07-10
  • 2017-04-29
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多