2017-09-23 121 views
0

我無法弄清楚如何呈現父組件,在頁面的一部分上顯示列表中的合同列表,以及當用戶單擊其中一個組件時,在頁面的其他部分顯示該特定合同的詳細信息。渲染vue.js組件並傳入數據

這裏是我的苗條文件:

#contracts_area 
    .filter-section 
    ul 
     li.filter-item v-for="contract in contractsAry" :key="contract.id" @click="showContract(contract)" 
     | {{ contract.name }} 
    .display-section 
    component :is="currentView" transition="fade" transition-mode="out-in" 

script type="text/x-template" id="manage-contracts-template" 
    div 
    h1 Blank when page is newly loaded for now 

script type="text/x-template" id="view-contract-template" 
    div :apply_contract="showContract" 
    h1#display-item__name v-name="name" 

的javascript:

Vue.component('manage-template', { 
    template: '#manage-contracts-template' 
    }); 

    Vue.component('view-contract', { 
    template: '#view-contract-template', 
    props: ['show_contract'], 
    data: function() { 
     return { 
     name: '' 
     } 
    }, 
    methods: { 
     showContract: function(contract) { 
     return this.name = contract.name 
     } 
    } 
    }); 

    Vue.http.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content'); 
    var contractsResource = Vue.resource('/all_contracts{/id}.json'); 

    var contracts = new Vue({ 
    el: '#contracts_area', 
    data: { 
     currentView: 'manage-template', 
     contractsAry: [], 
     errors: {} 
    }, 
    mounted: function() { 
     var that = this; 
     contractsResource.get().then(
     function(res) { 
      that.contractsAry = res.data; 
     } 
    ) 
    }, 
    methods: { 
     showContract: function(contract) { 
     this.currentView = 'view-contract' 
     } 
    } 
    }); 

基本上我想這樣,當用戶點擊任何合同項目在.filter截面,它在.display部分顯示該合同的數據。我怎樣才能做到這一點?

回答

1

總之,您可以將值綁定到prop

.display-section 
    component :is="currentView" :contract="currentContract" 

視圖合同

props: ['contract'] 

合同面積

data: { 
    currentContract: null, 
}, 
methods: { 
    showContract: function(contract) { 
    this.currentView = "view-contract"; 
    this.currentContract = contract; 
    } 
} 

有多種方式在Vue的傳遞數據。

  1. 將值綁定到props。使用ref直接調用子組件的方法。
  2. Custom Events。請注意,要全局傳遞事件,您需要一個全局事件總線。
  3. 真理的單箇中央源(即vuex

我已經說明的方法1,2,3在Codepen

注意次和第三方法將後只工作你的組件已經被渲染。在你的情況下,由於你的currentView組件是動態的,當用戶點擊時,display-section組件還不存在;它將不會收到任何事件。所以他們的內容一開始就是空的。

要解決此問題,您可以直接從子組件中訪問mounted()中的$parent,但是這會在它們之間創建耦合。另一種解決方案是創建組件,但它們是conditionally displaying。另一個解決方案將等待,直到子組件被安裝,然後發射事件。

如果您的需求很簡單,我建議綁定值到道具(),否則您可以考慮使用類似vuex的東西。

+0

完美,非常感謝您的幫助!感謝您的深入解答,對我的巨大幫助,因爲我剛剛開始使用Vue。 – asalgan