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

2019-09-16 14:57:43 +08:00
 selfcreditgiving

父组件:

<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

2747 次点击
所在节点    问与答
8 条回复
noe132
2019-09-16 15:04:22 +08:00
这是 vue 2.x 的默认行为。
如果你不希望样式直接传递下去,请加一层 div
selfcreditgiving
2019-09-16 15:15:56 +08:00
@noe132 加一层 div 确实是可以,就是代码会多了一个缩进了,不知道有没有 类似自动加 uid 的方法,给这个组件的根元素自动加上 id 是一个唯一 ID。css 里面这个好像不好写
shintendo
2019-09-16 15:23:47 +08:00
加 id 有什么用,你.wrap 不还是能选到
optional
2019-09-16 15:25:51 +08:00
没办法, 一个不是办法的办法就是 子组件的根元素的 class 为组件名
nigelvon
2019-09-16 15:33:10 +08:00
常见方案就是在所有组件顶层标签以固定规则加一个 class
selfcreditgiving
2019-09-16 15:36:43 +08:00
@shintendo
@optional
看来还是 @noe132 提供的方法最简单了,就先用这种方法了
selfcreditgiving
2019-09-16 15:53:52 +08:00
想起来了,加多一层 div 有个问题,因为 高度用百分比 ,必须要 最近一个父元素有设置过有具体的高度值(固定的 px 或者 从更上一层一直继承下来的百分比)。
那么加多一层 div 还需要 在这个空的 div 上加一个 in-line 样式 height:100%; 才可以。 这样又不简单了
shintendo
2019-09-16 15:57:35 +08:00
@selfcreditgiving 我觉得没有毛病,这个空的 div 不加任何样式的话,那么它的样式相当于是由父组件控制的,给多少高度是父组件的事

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/601178

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX