Without scoped
Parent component App.vue
<template>
<div class="app">
<HelloWorld />
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
components: {
HelloWorld,
},
};
</script>
<style lang="less">
// 在父组件中操作子组件的样式,没什么问题,正常生效!
h1 {
background-color: pink;
}
</style>
Child component HelloWorld.vue
<template>
<div class="hello">
<h1>Hello World</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
The compiled style and structure are as shown in the figure below. The background color of h1 turns pink, which is reasonable!
Add scoped
Parent component App.vue
<style lang="less" scoped>
h1 {
background-color: pink;
}
</style>
The compiled style and structure are as shown in the figure below, and the h1 background does not take effect!
Reason explanation
After adding scoped
1. Vue will add a unique attribute to all nodes of the current component and the root node of subcomponents
2. The compiled style will also automatically add this attribute in the form of a compound selector (attribute selector)
3. For example, what you wrote h1 { background-color: pink; }
, the original intention is to manipulate the h1 tag of the sub-component, the actual compiled style may be h1[data-v-7ba5bd90] { background-color: pink; }
, but! H1 node subcomponents and do not have this property, it h1[data-v-7ba5bd90] { background-color: pink; }
will not hit the h1 tag, it will not take effect!
How to deal with it
Parent component App.vue
<style lang="less" scoped>
/deep/ h1 {
background-color: pink;
}
</style>
The solution principle is to ensure that the compiled h1 style is not added to the composite selector (attribute selector), the compilation result is as shown in the figure below