2017-03-09 185 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>