Vue 里有 React.Fragment 之类的东西吗?

新手上路,请多包涵

在 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 许可协议

阅读 1.1k
2 个回答

Vue 中缺少第一方 Fragment 组件让我抓狂!

我看过 vue-fragment npm 包,但它让我对他们正在做的事情感到紧张,并且觉得必须有更好的方法。

我想出了一个非常轻量级的东西……它之所以有效,是因为允许功能组件返回多个根节点。

然而,这并不像 Reacts 那样 100% 有效。例如,在 React 中,您实际上可以使用 React.Fragment 作为应用程序中的根节点。这似乎只在你已经在一个组件中时才在 Vue 中起作用(即:它不能是你的基础组件的根节点)。

 const Fragment = {
  functional: true,
  render: (h, ctx) => ctx.children
}

使用它…

 <Fragment>
  <div>Div 1</div>
  <div>Div 2</div>
</Fragment>

超级好用…

 {someCondition && (
  <Fragment>
    <div>yay i can use multiple nodes</div>
    <div>:)</div>
  </Fragment>
)}

<div>
  Some inline text {condition ? (
    <Fragment>now I can use <strong>html</strong> and {variables}</Fragment>
  ) : (
    <Fragment>So many possibilities</Fragment>
  )}
</div>

原文由 Roi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题