31-Vue脚手架-scoped样式
我们先思考一个问题,如果对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)
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
2020-10-27 第一课 机器学习与数学分析