在 React 中,我可以做这样的事情:
// parent component
export default (){
return (
<div>
<div>1</div>
<ChildComponent />
<div>5</div>
</div>
);
}
// child component
export default (){
return (
<React.Fragment>
<div>2</div>
<div>3</div>
<div>4</div>
</React.Fragment>
);
};
// compiled html tags in browser .
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
但是在 Vue 中,当我做同样的事情时,事情就不同了。
// parent component
<template>
<div>
<div>1</div>
<child-component />
<div>5</div>
</div>
</template>
<script>
import childComponent from 'path/to/childComponent';
export default {
components: { childComponent }
}
</script>
-------------------------------------------------------------
// child component
<template>
<div id='have_to_write_in_vue'>
<div>2</div>
<div>3</div>
<div>4</div>
<div>
</template>
// compiled html tags in browser .
<div>1</div>
<div id='have_to_write_in_vue'>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div>5</div>
不同之处在于 ‘DIV’ 标签在 Vue 中不在同一级别。我该如何处理?
我问这是因为出现无用的嵌套时出了点问题。
原文由 RickyChan 发布,翻译遵循 CC BY-SA 4.0 许可协议
视图 2
包 Vue-fragment 促进了 vue 2 的无根组件。
视图 3
Vue 3 官方支持多根节点组件(片段) https://v3-migration.vuejs.org/new/fragments.html