请教个关于 vue3 中根节点需不需的问题

2022-07-14 10:47:08 +08:00
 yezheyu

vue 新手,最近在写 demo 时遇到个问题困惑着我,像请教下大家

vue2 中每个组件的的模板必须有一个根节点,vue3 就是非必须,但我实际测试也必须套个 div ,这是为什么?

下面的 son 组件中如果没有根节点,在实际网页中 vue 就不会为其渲染一个容器 div 包裹其模板中标签,导致我在其父组件中直接设置在子组件上的宽高失效

// son 组件
<template>
	<span>我是 son 组件</span>
	<span>我是 son 组件</span>
</template>

// father 标签
<template>
	<span>我是 father 组件</span>
	<son class="son" />
</template>

<style scoped>
.son {
	width: 100px;
	height: 100px;
	background-color: pink;
}
</style>

// vue 渲染出的 html 结构,子组件中没有承载高度的 div
<div id="app" data-v-app>
	<span data-v-7ba5bd90<template>
	<div>
		<span>我是 son 组件</span>
		<span>我是 son 组件</span>
	</div>

当我给 son 组件添加一个根标签后,因为最外层有个宽高承载对象,我设置的宽高就会生效

// son 组件
<template>
	<div>
		<span>我是 son 组件</span>
		<span>我是 son 组件</span>
	</div>
</template>

// father 组件
<template>
	<span>我是 father 组件</span>
	<son class='son'/>
</template>

<style scoped>
.son {
	width: 100px;
	height: 100px;
	background-color: pink;
}
</style>

// vue 渲染出的 html 结构,有承载样式的 div ,son 组件身上的宽高和背景色生效
<div id="app" data-v-app>
	<span data-v-7ba5bd90>我是 father 组件</span>
	<div class="son" data-v-7ba5bd90>
		<span>我是 son 组件</span>
		<span>我是 son 组件</span>
	</div>
</div>

那 Vue3 允许模板没有根节点有啥意义呢?大多情况下,只要是需要为子组件设置大小,岂不是都需要为子组件添加一个根节点?

另一个问题:

如果子组件必须有一个根节点,那为 son 组件标签设置宽高样式是像上面那样设置在其 father 组件的 style 中,还是像下面设置在自身的 style 中呢?

// son 组件
<template>
	<div class='container'>
		<span>我是 son 组件</span>
		<span>我是 son 组件</span>
	</div>
</template>

<style scoped>
.container {
	width: 100px;
	height: 100px;
	background-color: pink;
}
</style>

// father 组件,只设置布局,不设置 son 组件的宽高
<template>
	<span>我是 father 组件</span>
	<son class='son'/>
</template>

<style scoped>
.son {
	float:right;
}
</style>

son 组件把宽高设置在自身,那可以保证每个使用 son 组件的人拿到的 son 组件的大小都是一致的,不用重复的去设置,但有个问题是 son 组件的布局样式又写到 father 组价上,一个标签(把组件当做 html 标签看)的样式被放到两个地方会不会有些混乱?

像上面那样如果把宽高和布局都设置在 father 组件中,也会有个问题,组件的大小一般不是固定死吗?方便每个人使用都一样?写到 father 组件中感觉怪怪的,而且 son 组件每用到一次,就要在其使用的父组件中再设置一遍宽高,岂不是很麻烦?

所以实际开发中应该大家都使用哪种方式呢?

1192 次点击
所在节点    程序员
5 条回复
zcf0508
2022-07-14 10:54:57 +08:00
父组件:

<template>
<span>我是 father 组件</span>
<div class='son'>
<son />
</div>
</template>
lin07hui
2022-07-14 10:58:35 +08:00
doommm
2022-07-14 11:02:24 +08:00
SniperXu
2022-07-14 16:09:40 +08:00
如果没有根节点,transition 也会失效,之前踩过坑。。。
sjhhjx0122
2022-07-14 16:23:21 +08:00
很多时候还是需要的,所以我还是把根节点加上的

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

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

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

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

© 2021 V2EX