【问题标题】:How do we create nested Vue Components passing other elements as their children我们如何创建嵌套的 Vue 组件,将其他元素作为子元素传递
【发布时间】:2017-08-23 19:27:58
【问题描述】:

在 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 中我必须能够将其内容放在某个地方。

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

【问题讨论】:

标签: vue.js components vuejs2 vue-component


【解决方案1】:

您可以使用 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.

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多