首页 > 解决方案 > 在 vue 组件中使用样式的最佳实践是什么?

问题描述

我使用 vue cli 创建一个项目,但我的样式有“错误”

我只是测试一个有 3 行 20vh 50vh 30vh 的组件

<template>
    <div class="gridContact">
        <div class="one">1</div>
        <div class="two">2</div>
        <div class="three">3</div>
    </div>
</template>
<style scoped>
.gridContact {display: grid; grid-template-areas: 'one' 'two' 'three'; box-sizing: border-box;}
    .one {grid-area: one; background: rebeccapurple; box-sizing: border-box; height: 20vh; }
    .two {grid-area: two; background: cadetblue;  box-sizing: border-box; height:50vh;}
    .three {grid-area: three; background: coral;  box-sizing: border-box; height: 30vh; }
</style>

还有我的 app.vue

*{padding: 0; margin: 0; box-sizing: border-box;}

我得到了这种风格(需要的风格)

在此处输入图像描述

但是,如果我刷新页面,我得到了这个破坏样式的空白,然后如果再次重新加载它看起来不错,然后如果我刷新我得到相同的空白,为什么?

在此处输入图像描述

在开发人员工具上检查此行为时,我看到注入了此属性,当然该边距不是由我插入的,我认为这是在 vue 中造成的行为,也许是作用域属性?但是为什么呢?干什么用的?如何解决?

在此处输入图像描述

标签: htmlcssvue.jsvuejs2

解决方案


正如你不知道身体的margin-bottom应用是从哪里开始的,就像在下面的例子中我故意添加margin-bottom到身体并应用你的样式一样。

.gridContact {display: grid; grid-template-areas: 'one' 'two' 'three'; box-sizing: border-box;}
    .one {grid-area: one; background: rebeccapurple; box-sizing: border-box; height: 20vh; }
    .two {grid-area: two; background: cadetblue;  box-sizing: border-box; height:50vh;}
    .three {grid-area: three; background: coral;  box-sizing: border-box; height: 30vh; }

body{
  margin-bottom:50px;
}

*{padding: 0px; margin: 0px; box-sizing: border-box;}
<body>
<div class="gridContact">
      <div class="one">1</div>
      <div class="two">2</div>
      <div class="three">3</div>
  </div>
 </body>

现在我包括!important强制应用我的 css 样式并且它起作用了。

.gridContact {display: grid; grid-template-areas: 'one' 'two' 'three'; box-sizing: border-box;}
    .one {grid-area: one; background: rebeccapurple; box-sizing: border-box; height: 20vh; }
    .two {grid-area: two; background: cadetblue;  box-sizing: border-box; height:50vh;}
    .three {grid-area: three; background: coral;  box-sizing: border-box; height: 30vh; }

body{
  margin-bottom:50px;
}

*{padding: 0px !important; margin: 0px !important; box-sizing: border-box;}
<body>
<div class="gridContact">
      <div class="one">1</div>
      <div class="two">2</div>
      <div class="three">3</div>
  </div>
 </body>


推荐阅读