vue style标签scoped属性作用
- 限制加了scoped属性的样式仅在当前组件生效
- 如果不加scoped标签样式则作用在全局,
- 加了scoped标签的组件样式仍可受到作用在全局的样式的影响
- 组件中可使用ref代替id去使用,样式最好不要通过id去写
组件懒加载和组件未使用scoped属性的影响
懒加载方式导入组件:
- 父组件:
<template>
<div id="app">
<button @click="show2 =!show2">按钮</button>
<CPOne />
<CPTwo v-if="show2" />
</div>
</template>
<script>
import CPOne from './components/CPOne.vue'
export default {
name: 'App',
components: {
CPOne,
CPTwo: () => import('./components/CPTwo.vue')
},
data() {
return {
show2: false
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
- 子组件1:
<template>
<div id="CPOne" class="CPOne">
<h4 class="h4">我是组件一,我会受影响吗?</h4>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
- 子组件2:
<template>
<div id="CPTwo" class="CPTwo">我是组件2</div>
</template>
<script>
export default {
}
</script>
<style >
.h4 {
background: green;
}
</style>
- 实现效果:
非懒加载方式导入组件:
- 组件1:(仅组件1代码不同!)
<template>
<div id="app">
<button @click="show2 =!show2">按钮</button>
<CPOne />
<CPTwo v-if="show2" />
</div>
</template>
<script>
import CPOne from './components/CPOne.vue'
import CPTwo from './components/CPTwo.vue'
export default {
name: 'App',
components: {
CPOne,
CPTwo
},
data() {
return {
show2: false
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
- 实现效果: