【问题标题】:How to modify the styling of a component from the parent?如何从父级修改组件的样式?
【发布时间】:2018-04-21 14:45:18
【问题描述】:

我需要从父级修改 Vue 组件的一些 CSS 属性。它将覆盖组件中定义的 CSS。

我首先期望对于组件<my-component>,我可以直接从父元素中对其进行样式设置,就像任何其他元素一样:

my-component {
    font-weight: bolder;
}

这不起作用。

我尝试的第二个解决方案是将 prop 传递给组件,其中包含要在样式中使用的相关信息。这可行,但我仍然希望有一个更接近继承机制的解决方案(其中父项的设置优先于子项的设置,类似于设置<b> 元素的样式)。

有这样的机制吗?

【问题讨论】:

  • 向子组件的根元素添加一个类(如class="my-component"),然后您可以使用该类.my-component从父作用域添加样式。
  • @thanksd:我刚刚测试了您的解决方案,它运行良好,谢谢!你能把它变成一个答案吗?出于好奇,您知道为什么我的问题中的解决方案 1 不起作用(设置组件名称的样式) - 因为通过其类进行样式设置是可以的?

标签: css vue.js vue-component


【解决方案1】:

当 Vue 呈现组件的模板时,自定义组件标签将被替换为其模板定义。因此,尝试在 CSS 中选择自定义组件的标签是行不通的,因为该标签不在 DOM 中。

只需将class 属性添加到子组件的根元素(因为这是插入到DOM 中代替自定义组件标记的内容)。为了理智起见,我只是让类名与组件同名。然后,您可以通过.my-component 在 CSS 中的任何位置选择组件。

这是一个简单的例子:

Vue.component('my-component', {
  template: `<div class="my-component">Foo</div>`,
})

new Vue({ el: '#app' })
.my-component { color: goldenrod; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <my-component/>
</div>

【讨论】:

    【解决方案2】:

    灵感:

    var comp = {
      template: '<p><slot></slot></p>'
    }
    
    new Vue({
      el: '#app',
      data: {
        inParent: true
      },
      components: {
        comp
      },
      methods: {
        change () {
          this.inParent = !this.inParent
        }
      }
    })
    .blue {
      background-color: blue
    }
    <div id="app">
      This button is in parent:
      <button @click="change">change child style</button>
      <comp :class="{blue: inParent}">This is child component</comp>
    </div>
    
    <script src="https://unpkg.com/vue"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-10
      • 2022-11-05
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多