文章目錄
- 一、scoped是什么
- 二、應用案例
- 1.使用代碼
- 2.原理
- 3父組件App未添加scoped影響
一、scoped是什么
我們知道vue為了防止css樣式污染,在每個組件中提供了 scoped屬性進行限定css作用域;當<style>
標簽有 scoped 屬性時,它的 CSS 只作用于當前組件中的元素。
- 作用:讓樣式在局部生效,防止沖突。
- 寫法:
<style scoped>
二、應用案例
1.使用代碼
School.vue
<template><div class="demo"><h2 class="title">學校名稱:{{name}}</h2><h2>學校地址:{{address}}</h2></div>
</template><script>export default {name:'School',data() {return {name:'vue學院',address:'上海黃浦區',}}}
</script><style scoped>.demo{background-color: skyblue;}
</style>
Student.vue
<template><div class="demo"><h2 class="title">學生姓名:{{name}}</h2><h2 class="sex">學生性別:{{sex}}</h2></div>
</template><script>export default {name:'Student',data() {return {name:'張三',sex:'男'}}}
</script><style lang="less" scoped>.demo{background-color: pink;.sex{font-size: 50px;background: red;}}
</style>
App.vue
<template><div><h2 class="title">hello world</h2><School></School><hr><Student></Student></div>
</template><script>import Student from './components/Student.vue';import School from './components/School.vue';export default {name:'App',components:{Student,School},data() {return {}},}
</script><style scoped>.title{color: red;}
</style>
2.原理
我們可以看到,各自組件加上scoped屬性之后,對應的樣式標簽元素會隨機生成一個
[data-v-2232xxxx]
這樣的屬性,來保證每個組件樣式互不干擾。
代碼如下(示例):
3父組件App未添加scoped影響
父組件的樣式會應用到子組件上