vue的scoped注意事项

一:什么是scoped?

        在vue中,scoped通常用来限制变量的作用域。在组件中,可以让每个组件都可以拥有自己的作用域,这样组件模板更加灵活和可读性更高。如果项目中所有的页面和组件都添加了scoped属性,可以让项目模块化,减少很多不知名的布局bug。

二:不使用scoped的情况

1.目录创建

        使用vue创建如图所示目录

目录结构 

2.父页面(fatherPage)代码如下 

<template>
    <div class="home">
        <div class="head">
            this is a title
        </div>
        <div class="content">
            content...content...content...content...content...content...
        </div>
        <div class="foot">
            from:csdn:暴怒的代码 @ ID:c18559787293
        </div>
        <son-component></son-component>
    </div>
</template>

<script>
    import sonComponent from './components/sonComponent.vue'
    export default {
        components:{sonComponent}
    }
</script>

<style lang="scss">
    .home{
        width: 1366px;
        height: 768px;
        background: pink;
        text-align: center;
        .head{
            font-size: 34px;
            font-weight: 600;
            font-family: 'Courier New', Courier, monospace;
        }
    }
</style>

3.子组件(sonComponent)代码如下

<template>
    <div class="home">
        <div class="content">this is sonComponent content</div>
    </div>
</template>

<script>
</script>

<style lang="scss">
    .home{
        width: 100px;
        height: 100px;
        background: blue;
        .content{
            color: greenyellow;
        }
    }
</style>

3.运行效果 

        通过代码,我们可以看出,在父页面中没有给定content的样式,而在子组件中给了content的样式。页面运行之后,父组件的content样式变成了子组件里渲染的样式,这说明子组件的content样式污染了父页面的content样式。

运行效果图 

 三:解决办法

1.添加scoped属性

        我们在子组件的style样式上添加‘scoped’即可解决错误渲染的问题,当然为了习惯性,我们在父页面也添加scoped,这样便于以后的引用等。

 fatherPage

sonComponent 

 2.正确运行效果

         这次我们可以看到,运行就不会产生错误的渲染了。

正确效果图 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暴怒的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值