在 Vue js 中从 parent 定义 child 组件的布局

defining the layout of child component from parent in Vue js

我是 Vue 新手,正在使用 Vue 2.2.1。我想知道是否可以创建一个可重用的组件,其布局可以由 parent 定义。例如,考虑以下伪代码:

// Parent template
<template>
  <ul>
    <li v-for="item in items">
      <item-component :id="item.id">
        <h1><item-title /></h1>
        <p>
          <item-description />
        </p>
      </item-component>
    </li>
  </ul>
</template>


// Child definition
<script>
export default {
  data() {
    return {
      title: '',
      description: ''
    }
  }
  create() {
    // do some async fetch
    fetch(this.id)
      .then((result) {
        this.$data.title = result.title
        this.$data.description = result.description
      })
  }
}
</script>

所以,用例是child组件负责通过id获取数据,而parent负责布局数据。这样,我可以将获取逻辑保留在一个地方,但可以在不同的地方按照我的需要重新格式化数据。

不确定这是否可能。我想我可以将 child 的获取功能提取到混入中,但随后我必须为每个布局变体创建一个新组件。在 Vue 中推荐的处理方式是什么?

一般来说,当您希望 parent 包含 child 中的内容时,方法是通过 slot。然而,在一个典型的插槽内部,作用域是 parent 的作用域,这意味着它无法访问 child.

中的数据

在你的情况下,你会想要使用 scoped slot,这是 child 能够将一些信息传递回 parent 以供使用的地方。

// Parent template
<template>
  <ul>
    <li v-for="item in items">
      <item-component :id="item.id">
        <template scope="props">
            <h1>{{props.title}}</h1>
            <p>
              {{props.description}}
            </p>
        </template>
      </item-component>
    </li>
  </ul>
</template>


// Child definition
<script>
export default {
  template:"<div><slot :title='title' :description='description'></slot></div>",
  data() {
    return {
      title: '',
      description: ''
    }
  }
  create() {
    // do some async fetch
    fetch(this.id)
      .then((result) {
        this.$data.title = result.title
        this.$data.description = result.description
      })
  }
}
</script>