V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
selfcreditgiving
V2EX  ›  问与答

vue 子组件的根节点 样式 会受到父组件的影响,应该如何比较优雅的避免这个情况?

  •  
  •   selfcreditgiving · 2019-09-16 14:57:43 +08:00 · 2728 次点击
    这是一个创建于 1656 天前的主题,其中的信息可能已经有所发展或是发生改变。

    父组件:

    <template>
        <div class="wrap">
        	<header></header>
            <main>
            	<ChildCompoment></ChildCompoment>
            </main>
        </div>
    </template>
    <style lang="scss" scoped>
    	.wrap {
        	height: 100%;
        }
    </style>
    

    子组件:

    <template>
        <div class="wrap"></div>
    </template>
    <style lang="scss" scoped>
    
    </style>
    

    上面的代码 子组件的 根节点元素( class 为 wrap )也会受到影响。

    引用 Vue-Loader 文档的说明:

    Child Component Root Elements
    With scoped, the parent component's styles will not leak into child components. However, a child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. This is by design so that the parent can style the child root element for layout purposes.

    那这样的话,我要在子组件的根节点上写 class 就要十分小心,要考虑父组件是不是有用到了。
    有什么比较优雅的方式,让我可以在每个组件里自由的写 class

    8 条回复    2019-09-16 15:57:35 +08:00
    noe132
        1
    noe132  
       2019-09-16 15:04:22 +08:00
    这是 vue 2.x 的默认行为。
    如果你不希望样式直接传递下去,请加一层 div
    selfcreditgiving
        2
    selfcreditgiving  
    OP
       2019-09-16 15:15:56 +08:00
    @noe132 加一层 div 确实是可以,就是代码会多了一个缩进了,不知道有没有 类似自动加 uid 的方法,给这个组件的根元素自动加上 id 是一个唯一 ID。css 里面这个好像不好写
    shintendo
        3
    shintendo  
       2019-09-16 15:23:47 +08:00
    加 id 有什么用,你.wrap 不还是能选到
    optional
        4
    optional  
       2019-09-16 15:25:51 +08:00
    没办法, 一个不是办法的办法就是 子组件的根元素的 class 为组件名
    nigelvon
        5
    nigelvon  
       2019-09-16 15:33:10 +08:00
    常见方案就是在所有组件顶层标签以固定规则加一个 class
    selfcreditgiving
        6
    selfcreditgiving  
    OP
       2019-09-16 15:36:43 +08:00
    @shintendo
    @optional
    看来还是 @noe132 提供的方法最简单了,就先用这种方法了
    selfcreditgiving
        7
    selfcreditgiving  
    OP
       2019-09-16 15:53:52 +08:00
    想起来了,加多一层 div 有个问题,因为 高度用百分比 ,必须要 最近一个父元素有设置过有具体的高度值(固定的 px 或者 从更上一层一直继承下来的百分比)。
    那么加多一层 div 还需要 在这个空的 div 上加一个 in-line 样式 height:100%; 才可以。 这样又不简单了
    shintendo
        8
    shintendo  
       2019-09-16 15:57:35 +08:00
    @selfcreditgiving 我觉得没有毛病,这个空的 div 不加任何样式的话,那么它的样式相当于是由父组件控制的,给多少高度是父组件的事
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2663 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 15:20 · PVG 23:20 · LAX 08:20 · JFK 11:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.