首页 > 解决方案 > :first-child 样式未在 Vue 组件中应用

问题描述

问题:

通常第一个<User>应该有margin-left: 0px并且应该与其他元素对齐到左边,但这不起作用,正如您在下面的屏幕截图中看到的那样。有人知道如何正确解决这个问题吗?

在此处输入图像描述

sidebar.scss代码:

.user {
  margin-left: -8px;

  &:first-child {
    margin-left: 0;
  }
}

Sidebar.vue代码

<template>
  <section class="sidebar">
    <slot></slot>
  </section>
</template>

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

<style scoped lang="scss">
  @import 'sidebar';
</style>

Profile.vue代码

<template>
  <main>
    <Sidebar>
      <Header text="Members" :button="{text: 'Edit'}" hasBorder="true"></Header>
      <User img="..."></User>
      <User img="..."></User>
      <User img="..."></User>
      <User img="..."></User>
      <Button color="grey" isRounded="true" isIconOnly="true"></Button>
    </Sidebar>
  </main>
</template>

User.vue代码:

<template>
  <div class="user">
    <img v-if="this.img" :src="this.img" :alt="this.name">
    <div v-if="!this.img"></div>
    <h6 v-if="this.name">{{this.name}}</h6>
    <slot></slot>
  </div>
</template>

标签: cssvue.jssassscope

解决方案


用于::v-deep更改scopedcss。

我已经回答了这个问题,但我有一个旧的和更具描述性的答案,这可能有助于您了解用法https://stackoverflow.com/a/56698470/7358308

https://vue-loader.vuejs.org/guide/scoped-css.html#deep-selectors

注意:不要使用/deep/,因为它已被弃用,并且当您使用预处理器时,>>>组合器也不起作用sass

::v-deep {
  .user {
    margin-left: -8px;

    &:first-child {
     margin-left: 0;
   }
  }

}

推荐阅读