2016-03-01 420 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