这似乎是一个相当基本的问题,但我似乎找不到一个明确的(甚至是有效的)答案.

我有我的根实例:

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次,但都没用.正确的方法是什么?请记住,我希望引用根目录中的数据,而不是创建具有自己作用域的副本.

编辑:试图使用props ,下面是列表组件,它也不起作用:

var EventsList = Vue.extend({

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

props: ['events']

}

推荐答案

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

文件规定:

请注意,如果要传递的props 是对象或数组,则会通过引用传递.在子对象中改变对象或数组本身将影响父状态,无论您使用的绑定类型如何.

因此,当您将同一对象作为props 传递时,它将在所有组件中使用.

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>

Vue.js相关问答推荐

使用项目和字段,列跨度为 2 的 Bootstrap-vue 表

如何向 添加方法和 v-model?

有没有办法在 Quasar 中为明暗模式创建我自己的 colored颜色 ?

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

v-slot: activator 中 {attrs} 参数的作用是什么?

vue.js 在 App.vue 中获取路由名称

Vue CLI - 编译后将配置文件保留为外部

正确使用 Vue $refs

未捕获的错误:[vue-composition-api] 必须在使用任何函数之前调用 Vue.use(plugin)

如何将Vue的主应用程序渲染到body元素?

如何使用 vue-resource 添加额外的标头来发布请求?

Vue.js 无法切换字体真棒图标

Vue 动态组件事件绑定

如何将数据传递给 Vue.js 中的路由视图

Vuejs获取事件正在调用的元素?

如何从 Vuex 操作访问 Vuex 状态属性?

Vue.js 3 - 替换/更新react性对象而不会失go react性

在 Vuejs 中放置 firebase.auth().onAuthStateChanged() 的位置

将 Vue props与默认值合并

超过最大调用堆栈大小 Vuetify