【问题标题】:Scoped Styles are always overwritten范围样式总是被覆盖
【发布时间】:2020-09-12 03:05:17
【问题描述】:

我目前正在学习 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>

【问题讨论】:

标签: css vue.js sass scope


【解决方案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

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2020-05-27
    • 2019-02-22
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多