我们先思考一个问题,如果对School 和 Student应用样式的话,一般是使用如下方式:
src/components/School.vue
<template> <div class="demo"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> export default{ // eslint-disable-next-line vue/multi-word-component-names name:"School", data(){ return{ name:"东华理工大学", address:"江西南昌", } } } </script> <style scoped> .demo{ background-color: skyblue; } </style>
src/components/Student.vue
<template> <div class="demo2"> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> </div> </template> <script> export default{ // eslint-disable-next-line vue/multi-word-component-names name:"Student", data(){ return{ name:"马铃薯", sex:"男", } } } </script> <style> .demo2{ background-color: orange; } </style>
但Vue是将所以组件的样式都加载到一块,目前只是"demo"和"demo2"没有冲突时可以正常使用,如果两个名字冲突,则会默认时候最后加载的样式,会导致冲突
scoped样式
作用:让样式在局部生效,防止冲突(因此在开发过程中,基本都会加上)
写法:<style scoped>
src/components/School.vue
<template> <div class="demo"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> export default{ // eslint-disable-next-line vue/multi-word-component-names name:"School", data(){ return{ name:"东华理工大学", address:"江西南昌", } } } </script> <!--scoped样式,可以让样式在局部生效,防止冲突--> <style scoped> .demo{ background-color: skyblue; } </style>
src/components/Student.vue
<template> <div class="demo"> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> </div> </template> <script> export default{ // eslint-disable-next-line vue/multi-word-component-names name:"Student", data(){ return{ name:"马铃薯", sex:"男", } } } </script> <!--scoped样式,可以让样式在局部生效,防止冲突--> <style scoped> .demo{ background-color: orange; } </style>
src/App.vue(无改动)
<template> <div> <!--学校的信息--> <School></School> <!--学生的信息--> <Student></Student> </div> </template> <script> // 引入Student组件 import Student from "@/components/Student.vue"; // 引入School组件 import School from "@/components/School.vue"; export default{ name:"App", components: { School: School, Student: Student } } </script>
src/main.js(无改动)
import Vue from "vue" import App from "./App.vue" // 阻止 vue 在启动时生成生产提示 Vue.config.productionTip = false new Vue({ el:"#app", render:h => h(App) })
标签:src,School,Vue,name,components,31,vue,scoped,Student From: https://www.cnblogs.com/REN-Murphy/p/17791085.html