一:什么是scoped?
在vue中,scoped通常用来限制变量的作用域。在组件中,可以让每个组件都可以拥有自己的作用域,这样组件模板更加灵活和可读性更高。如果项目中所有的页面和组件都添加了scoped属性,可以让项目模块化,减少很多不知名的布局bug。
二:不使用scoped的情况
1.目录创建
使用vue创建如图所示目录
目录结构
2.父页面(fatherPage)代码如下
<template>
<div class="home">
<div class="head">
this is a title
</div>
<div class="content">
content...content...content...content...content...content...
</div>
<div class="foot">
from:csdn:暴怒的代码 @ ID:c18559787293
</div>
<son-component></son-component>
</div>
</template><script>
import sonComponent from './components/sonComponent.vue'
export default {
components:{sonComponent}
}
</script><style lang="scss">
.home{
width: 1366px;
height: 768px;
background: pink;
text-align: center;
.head{
font-size: 34px;
font-weight: 600;
font-family: 'Courier New', Courier, monospace;
}
}
</style>
3.子组件(sonComponent)代码如下
<template>
<div class="home">
<div class="content">this is sonComponent content</div>
</div>
</template><script>
</script><style lang="scss">
.home{
width: 100px;
height: 100px;
background: blue;
.content{
color: greenyellow;
}
}
</style>
3.运行效果
通过代码,我们可以看出,在父页面中没有给定content的样式,而在子组件中给了content的样式。页面运行之后,父组件的content样式变成了子组件里渲染的样式,这说明子组件的content样式污染了父页面的content样式。
运行效果图
三:解决办法
1.添加scoped属性
我们在子组件的style样式上添加‘scoped’即可解决错误渲染的问题,当然为了习惯性,我们在父页面也添加scoped,这样便于以后的引用等。
fatherPage
sonComponent
2.正确运行效果
这次我们可以看到,运行就不会产生错误的渲染了。
正确效果图