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

Chr*_*ris 13 javascript 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();

}

});
Run Code Online (Sandbox Code Playgroud)

我有一个单独的组件,我想在其中列出存储在根实例中的事件.目前它看起来像这样:

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();
}
}
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用.我也试着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']

}
Run Code Online (Sandbox Code Playgroud)

nil*_*ils 6

使用props,您可以轻松地将相同的数据从父级传递给子级.由于我不知道你是如何将根实例和它们EventList连在一起的,所以我假设你把它注册为一个全局组件.

文件说明:

请注意,如果传递的prop是Object或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();

}

});
Run Code Online (Sandbox Code Playgroud)

活动列表:

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);
Run Code Online (Sandbox Code Playgroud)

在根vue实例模板中,您可以将根vue实例events作为events子组件中调用的属性传递:

<div class="app">
    <!-- events is passed using the :events prop -->
    <eventlist :events="events">
    </eventlist>
</div>
Run Code Online (Sandbox Code Playgroud)