Vue.js - 从组件内的根实例访问数据

Vue.js - access data from root instance within component

这似乎是一个相当基本的问题,但我似乎无法找到确定的(甚至有效的)答案。

我有我的根实例:

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']

}

这就是 "Props" 的用途:

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

如果您将 object/array 作为道具传递(您的 events 数据肯定是什么),它会自动双向同步 - 子项中的更改事件,父项中的更改事件.

如果您通过 props 传递简单值(字符串、数字 - 例如仅 event.name),则必须显式使用 .sync 修饰符:http://vuejs.org/guide/components.html#Prop_Binding_Types

Using props,您可以轻松地将相同的数据从父级传递给子级。由于我不知道您是如何将根实例和 EventList 链接在一起的,因此我假设您将其注册为全局组件。

文档指出:

Note that if the prop being passed down is an Object or an Array, it is passed by reference. Mutating the Object or Array itself inside the child will affect parent state, regardless of the binding type you are using.

因此,当您将同一个对象作为 prop 传递时,您将在所有组件中使用同一个对象。

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();

}

});

事件列表:

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>
this.$root.events

将引用根组件,“即 main.js 或 index.js 或 app.js” 无论您在哪个组件中,使用 props 都需要将其传递下去每个组件假设您想在第三个子组件中使用它。