Skip to content
On this page

uniapp 入门实战 11:解决给引入的组件添加 class,样式诡异问题


情境

  • 实际效果

    给 Comp 添加 class,蓝色边框贼诡异,为啥会显示成这个样式?

  • 正确效果:vue demo

代码

  • Comp.vue

    html
    <template>
      <view class="item">
        this is a item
        <view class="text"> this is a Comp </view>
      </view>
    </template>
    
    <script setup></script>
    
    <style>
      .item {
        padding: 20px;
        box-sizing: border-box;
      }
    
      .item .text {
        color: red;
        border: 1px solid;
        text-align: center;
    
        background: #00ff00;
      }
    </style>
    
  • index.vue

    html
    <template>
      <Comp class="Comp"></Comp>
    </template>
    
    <script setup>
      import Comp from "./Comp.vue";
    </script>
    
    <style scoped>
      .Comp {
        display: block;
        padding: 40px;
        border: 4px solid #0000ff;
        box-sizing: border-box;
      }
    </style>
    

没有想到为啥,就给 uniapp 提了一个 issues

总结

  • 原来是引入组件添加的 class,view 标签默认是未 display 属性,所以只要设置成 block 元素即可

参考文献

Released under the MIT License.