Skip to content

局部样式设置

  1. 防止组件之间样式名冲突

  2. 语法格式

    html
    <style scoped></style>

代码实现

  1. App.vue

    html
    <template>
        <div>
            <School></School>
            <Student></Student>
        </div>
    </template>
    
    <script>
        import Student from './components/Student.vue'
        import School from './components/School.vue'
    
        export default {
            name: 'App',
            components: {
                Student,School
            }
        }
    </script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .box {
            width: 300px;
            height: auto;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
        }
    </style>
  2. Student.vue

    html
    <template>
        <div class="box back">
            <h5>学生姓名:{{ name }}</h5>
            <h5>学生性别:{{ sex }}</h5>
            <h5>学生年龄:{{ age }}</h5>
        </div>
    </template>
    
    <script>
    export default {
        name: 'Student',
        data(){
            return {
                name: 'iGma',
                sex: '男',
                age: 21,
            }
        }
    }
    </script>
    
    <style scoped>
        .back {
            background-color: pink;
        }
    </style>
  3. School.vue

    html
    <template>
        <div class="box back">
            <h5>学校名称:{{ name }}</h5>
            <h5>学校地址:{{ address }}</h5>
        </div>
    </template>
    
    <script>
    export default {
        name: 'School',
        data(){
            return {
                name: '内蒙古农业大学',
                address: '内蒙古呼和浩特'
            }
        }
    }
    </script>
    
    <style scoped>
        .back {
            background-color: orange;
        }
    </style>
  4. 运行结果

基于 MIT 许可发布