2016-03-01 421 views
8

這似乎是一個相當基本的問題,但我似乎無法找到一個明確的(或甚至是工作)的答案。Vue.js - 從組件中的根實例訪問數據

我有我的根實例:

var vm = new Vue({ 
    el: '#app', 

    // Data 
    data: { 
     events: {} 
    }, 

    // Methods 
    methods: { 

    fetchEvents: function(){ 
     this.$http.get('/api/events').success(function(theseEvents) { 
     this.$set('events', theseEvents); 

     }).error(function(error) { 

     }); 

    } 
}, 

ready: function(){ 

    this.fetchEvents(); 

} 

}); 

而且我有,我想列出存儲在根實例的事件的獨立部件。目前看起來像這樣:

var EventsList = Vue.extend({ 

template: '<ul><li v-for="event in events"><h2>{{ event.title }}</h2><p>{{ event.body }}</p></li></ul>', 

data: function(){ 
    return { 
    events: {} 
    } 
}, 

methods: { 

    syncEvents: function(){ 
    this.$set('events', this.$parent.events); 
    } 

}, 

// When ready... 
ready: function(){ 
    this.syncEvents(); 
} 
} 

這似乎不起作用。我也試過this.$root.events無濟於事。什麼是正確的方式去做這件事?請記住,我想從根引用數據,而不是使用自己的作用域創建副本。

編輯:嘗試使用道具,這裏是列表組件,這也是不工作:

var EventsList = Vue.extend({ 

template: '<ul><li v-for="event in events"><h2>{{ event.title }}</h2><p>{{ event.body }}</p></li></ul>', 

props: ['events'] 

} 
+0

確定你不想使用與道具的雙向同步?這樣,你就不必緊密結合這兩個組件。 – nils

+0

對不起,我對此很新。你能解釋一下你的意思嗎?我把這些事件放在根實例中,因爲我希望將它們用在許多組件中。 – Chris

+0

這些組件是否會更改「事件」,還是隻讀?我會在一秒內解釋。 – nils

回答

3

Using props,你可以很容易地從母體傳遞相同的數據給孩子。由於我不知道如何將根實例和EventList鏈接在一起,我會假設您將其註冊爲全局組件。

的文檔狀態:

注意,如果支柱被向下傳遞是一個對象或Array,則通過引用傳遞。無論您使用何種綁定類型,在子對象內部突變對象或數組本身都會影響父狀態。

因此,當您將其作爲道具傳遞時,您將在所有組件中使用相同的對象。

var vm = new Vue({ 
    el: '#app', 

    // Data 
    data: { 
     events: {} 
    }, 

    // Methods 
    methods: { 

    fetchEvents: function(){ 
     this.$http.get('/api/events').success(function(theseEvents) { 
     this.$data.events = theseEvents; // You don't need to use $set here 

     }).error(function(error) { 

     }); 

    } 
}, 

ready: function(){ 

    this.fetchEvents(); 

} 

}); 

EVENTLIST:

var EventsList = Vue.extend({ 

template: '<ul><li v-for="event in events"><h2>{{ event.title }}</h2><p>{{ event.body }}</p></li></ul>', 

data: function(){ 
    return { 
    } 
}, 
props: { 
    events: Object, // assuming that your prop is an object 
}, 
} 

// Register the vue component globally, if you want to: 
Vue.component('eventlist', EventsList); 

在根VUE例如模板,你可以通過根VUE實例events爲在子組件稱爲events屬性:

<div class="app"> 
    <!-- events is passed using the :events prop --> 
    <eventlist :events="events"> 
    </eventlist> 
</div> 
1

這就是 「道具」 是:

http://vuejs.org/guide/components.html#Props

我你傳遞一個對象/數組作爲道具(您的events數據肯定會是),它會自動雙向同步 - 在子項中更改事件,它們在父項中更改。

如果你通過簡單的值(字符串,數字 - 例如,只event.name)通過道具,你必須明確地使用.sync修改:http://vuejs.org/guide/components.html#Prop_Binding_Types

+0

好吧,我剛剛完成了一些關於道具的閱讀。似乎我應該只需添加道具:['events']到模板的eventList組件中去?它不起作用... – Chris

+0

確保您在@nils全局註冊了您的組件,並且確保您將:events prop傳遞給其聲明的子項> – TechyTimo