2016-06-08 61 views
0

有什麼辦法可以將數據隱式傳遞給父級的所有子組件嗎?我在React中尋找類似context的東西。這裏是什麼,我試圖完成一個簡單的例子:如何將數據隱式傳遞給Vue中的所有子組件?

<body> 
    <my-component :my-prop="foo"></my-component> 
    <my-component :my-prop="bar"></my-component> 
</body> 

-

import MyComponent from './my-component'; 

new Vue({ 
    el: 'body', 
    components: { 
     MyComponent, 
    }, 
}); 

我想所有my-component的孩子不得不myProp訪問,而無需通過它記下來時間。 $root聽起來像一個好主意,但是接下來我不得不爲網頁上的每個組件創建一個虛擬主機,這也感覺不太好。

+0

你可以使用事件嗎? – gurghet

回答

0

從子組件,你可以得到父組件的屬性像

這個$ parent.myProp

https://vuejs.org/guide/components.html#Parent-Chain

編輯:創建函數在父母找物業:

getProperty: function(vueComp, propName) { 
    var p = vueComp.$parent; 
    while (p) { 
     if(p.hasOwnProperty(propName)){ 
     return p[propName]; 
     } 
     p = p.$parent; 
    } 

    return null; 
} 

使用它像:var x = getProperty("myProp");

+0

雖然這隻適用於一個級別,但我正在尋找可以無限傳遞道具的東西。 –

+0

@SebastianDeDeyne然後我看到只有一種方法 - 創建函數來查找屬性。我添加了它來回答。 –

相關問題