在Vue js中定义来自父级的子组件的布局

时间:2017-03-09 16:43:01

标签: vue.js vuejs2 vue-component

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

// 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>

因此,用例是子组件负责通过id获取数据,但父组件负责布局数据。这样,我可以将获取逻辑保存在一个地方,但重新格式化数据,但我想要在不同的地方。

不确定这是否可行。我想我可以将孩子的提取功能提取到mixin中,但是我必须为每个布局变化创建一个新的组件。在Vue中处理此问题的推荐方法是什么?

1 个答案:

答案 0 :(得分:0)

通常,当您希望父级在子级中包含内容时,执行此操作的方法是通过slot。在内部,一个典型的插槽,范围是父的范围,这意味着它无法访问子内的数据。

在您的情况下,您可能希望使用scoped slot,这是孩子能够将一些信息传递给父母使用的地方。

// 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>