范围样式始终会被覆盖

时间:2020-05-25 13:06:24

标签: css vue.js sass scope

我正在学习Vue,无法摆脱示波器问题。

问题profile.vue样式将继续覆盖sidebar.vue中的样式。边栏应使用此设置将其背景保持为红色,而配置文件页面中的部分应为蓝色。不应该在scoped标签中使用style标记此工作吗?

输出enter image description here

Profile.vue下面

<template>
  <main>
    <section>
      Test
    </section>
    <Sidebar></Sidebar>
  </main>
</template>

<script>
  import Sidebar from "../../components/sidebar/Sidebar";
  export default {
    name: "Profile",
    components: {Sidebar}
  }
</script>

<style scoped lang="scss">
  main {
    width: 100%;
    @include flex();

    section {
      width: 100%;
      background: blue;
      margin-left: $size*5;
    }
  }
</style>

Sidebar.vue下面

<template>
  <section>
    Test
  </section>
</template>

<script>
  export default {
    name: "Sidebar"
  }
</script>

<style scoped lang="scss">
  section {
    max-width: ($size*45);
    width: 100%;
    background: red;
  }
</style>

2 个答案:

答案 0 :(得分:1)

这里的问题是子组件的根元素是一个节

通过设计,父组件能够为子组件的根设置样式。 通常使用此功能,以便您可以轻松设置子组件的样式,添加边距,填充等。但是在您的情况下,这是有冲突的。

您所看到的:

<template>
  <div>
    <section>...</section>
    <your-component></your-component>
  </div>
</template>

您的作用域CSS所见:

<template>
  <div>
    <!-- I can style out here -->
    <section>...</section>
    <section>
    <!-- But I can't style in here -->
    </section>
  </div>
</template>

有范围的css不会进入组件,但是组件的根基基本上是在允许样式化的级别,并且由于它是一个部分,因此css选择器是有效的。

如果只是像这样包装子组件,就不会有冲突:

<template>
  <div>
    <section>...</section>
  </div>
</template>

您还可以使用不同的类等对它们进行样式设置。

这里是official docs

答案 1 :(得分:1)