作用域样式总是被覆盖

Scoped Styles are always overwritten

我目前正在学习 Vue,无法摆脱范围问题。

问题: profile.vue 样式不断覆盖 sidebar.vue 中的样式。侧边栏应使用此设置保持红色背景,而个人资料页面中的部分应为蓝色。不应该在 style 标记这项工作中做 scoped 吗?

输出

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>

这里的问题是你的子组件的根元素是一个部分

根据设计,父组件能够为子组件根设置样式。 通常,使用它是为了让您可以轻松地设置子组件的样式、添加边距、填充等。但在您的情况下,这是冲突的。

你看到的:

<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

以下是解释此行为的文档:

https://vue-loader.vuejs.org/guide/scoped-css.html#mixing-local-and-global-styles

这里已经回答了:

How to correctly use "scoped" styles in VueJS single file components?