In Vue.js, scoped styles are a feature that allows you to apply styles to a specific component without affecting the styles of other components. This is achieved by adding the scoped
attribute to the <style>
tag within a Vue component file. Here's how you can use scoped styles in Vue.js:
Create a Vue Component:
Assume you have a Vue component file, for example, MyComponent.vue
. The file structure might look like this:
html<!-- MyComponent.vue -->
<template>
<div class="my-component">
<p>This is my component!</p>
</div>
</template>
<script>
export default {
name: 'MyComponent',
// other component options...
}
</script>
<style scoped>
/* Scoped styles go here */
.my-component {
background-color: lightblue;
}
p {
color: green;
}
</style>
Add Scoped Styles:
In the example above, the <style>
tag has the scoped
attribute. This means that the styles defined inside the <style>
tag will only apply to elements within the scope of the current component.
html<style scoped>
/* Scoped styles go here */
.my-component {
background-color: lightblue;
}
p {
color: green;
}
</style>
The styles will only affect elements within the <template>
of the current component (MyComponent
in this case).
Result:
When the MyComponent
is used in another component or template, the styles will be scoped to the elements within the MyComponent
:
html<!-- AnotherComponent.vue -->
<template>
<div>
<my-component></my-component>
</div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent,
},
// other component options...
}
</script>
In this example, the styles applied to the .my-component
class and the p
element in MyComponent.vue
will only affect elements within the MyComponent
and won't leak to other components.
Scoped styles help in encapsulating styles within the scope of a component, making it easier to manage and preventing unintended side effects across your application.