2017-03-09 186 views
1

我是新来的Vue和使用Vue 2.2.1。我想知道是否有可能创建一个可重用的组件,其布局可以由其父组件定义。例如,考虑下面的伪代码:从父定义子组件的布局Vue公司JS

// 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的数据读取,但父负责铺设的数据。这样,我可以将抓取逻辑保留在一个地方,但是我想在各个地方重新格式化数据。

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

+0

使用范围的插槽。 https://vuejs.org/v2/guide/components.html#Scoped-Slots – Bert

回答

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>