Vue 3 style scoped would effect for components

198 Views Asked by At
<script setup lang="ts">
</script>

<template>
  <div>
    <el-button>a</el-button>
    <el-button>b</el-button>
  </div>
</template>
<style scoped>
  .el-button{
    margin-right:10px;
  }
</style>

I use vue2 before and I think .el-button would not effect for the el-button because of the scoped. But it effects with Vue 3.

I want to know why.

1

There are 1 best solutions below

0
On

Scoped style only affects the component in which it is defined. Hence, your current file. So, it is quite normal this 2 buttons to be affected by your "margin-right" property. But if you put another buttons to your another files/components, you will see they will not be affected by this "margin-right" setting. That's why, it is important to put "scoped" indicator not to mess things up.

But I have to note that, the experience I gained during my usage of Element-Plus showed me that your custom style settings crushed by Element-Plus component's built-in style bindings. To overcome this:

Option 1 is to put your style settings to a separate css file which will be loaded after the Element-Plus so that your styles are not be overwritten.

Option 2 is to use styles in a way:

<template>
    <div> 
        <el-button style="margin-right: 10px;"></el-button> 
    </div>
</template>

instead of:

<template>
    <div> 
        <el-button class="button-style"></el-button>
    </div>
</template>

<style scoped>
 .button-style{
   margin-right:10px;
 }
 </style>

In my opinion, your experience may caused by Element-Plus style overwrite matter instead of Vue version.