2017-05-26 22 views
1

我是Vue的新手,無法找到一種方法來實現類似Vue.js的React-like「Wrapper」組件,例如,一個可重用的datagrid組件使用第三方some-table組件和pagination組件。直觀上,datagrid將提供兩個組件需要的數據/道具/事件並控制它們之間的通信。在陣營,可以這樣做簡單,如像如何在Vue.js中創建'容器'組件

// inside <Datagrid /> 
<Table {...someProps} /> 
<Pagination {...otherProps} /> 

隨着Vue公司,這似乎是類似下面只能通過props到子組件

// inside Datagrid.vue 
<some-table v-bind="$props"></some-table> 

我不知道如果slots可能會有所幫助。我一直在努力的這個包裝組件需要它的孩子需要的所有props/events/slots,並將它們傳遞給它們,以便我可以利用它的所有功能,它是兒童(可能是一些第三方組件)提供的。此外,它也可能需要爲其子女之間的數據交換負責。雖然datagrid可能是一個插槽包裝,但如果tablepagination需要相同的data支持,我認爲應該位於datagrid。如何將這個data傳遞給插槽?

// Datagrid.vue 
<template> 
    <div> 
    <slot name="table"></slot> 
    <slot name="pagination"></slot> 
    </div> 
</template> 

<script> 
export default { 
    name: 'Datagrid', 
    data() { 
    return { 
     data: 'How to share it with table and pagination', 
    } 
    }, 
} 
</script> 

一些解決方案,我可以計算出:

  1. Render Functions,但我不認爲同謀需要在這種情況下
  2. 而是創建一個「容器」組件,只需打開到mixins,但這是否意味着我每次需要輸入數據網格時都必須輸入<pagination :total="total" :other-props="are-same-for-all-datagrids"></pagination>

在Vue中處理這種情況的任何示例?提前致謝!

+0

插槽是你想要什麼。 –

回答

2

你想用slots

Vue.component('wrapper', { template: '#wrapper' }) 
 

 
new Vue({ el: '#app' })
<!-- wrapper template --> 
 
<script type="text/x-template" id="wrapper"> 
 
    <div class="wrapper" style="background: beige; padding: 5px;"> 
 
    This is being wrapped: 
 
    <slot></slot> 
 
    </div> 
 
</script> 
 

 
<div id="app"> 
 
    <wrapper> 
 
    <div style="background: aliceblue;">I'm being wrapped!</div> 
 
    </wrapper> 
 
</div> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>

+0

感謝您的回答!例如,如果我有兩個插槽,並且將要插入的子組件需要相同的'tableData'屬性。如何將這個'tableData'傳遞給兩個插槽,這樣當父代更新時,兩個孩子都會得到通知? – mylostlenore

+0

只需傳遞與兩個組件的'tableData'屬性相同的變量即可。 – thanksd