我们如何创建嵌套的 Vue 组件将其他元素作为其子元素传递

How do we create nested Vue Components passing other elements as their children

在 React 中我会做这样的事情:

//ParentComponent.js
(<div>
  {this.props.children}
</div>)

//ChildComponent.js
(<div>
  I'm the child!
</div>)

//App.js
import ParentComponent
import ChildComponent

<ParentComponent>
  <ChildComponent />
  <span>Other element</span>
</ParentComponent>

我知道它们是不同的东西,但是我怎么能在 Vue 中做这样的事情呢?我想在 ParentComponent 的内容中传递 ChildElement,而在 ParentComponent 中我必须能够将其内容放在某个地方。

最接近这个想法的是什么?

您可以使用 slots 来做到这一点。

Vue.component("parent",{
  template:"<div><h1>I'm the parent component</h1><slot></slot></div>",
})

Vue.component("child", {
  template: "<div><h2>I'm the child component</h2></div>"
})

new Vue({
  el:"#app"
})

<div id="app">
  <parent>
    <child></child>
  </parent>
</div>

Example.