繁体   English   中英

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无济于事。 go 的正确方法是什么? 请记住,我想从根目录中引用数据,而不是用它自己的 scope 创建一个副本。

编辑:尝试使用道具,这里是列表组件,它也不起作用:

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 ,您可以轻松地将相同的数据从父级传递给子级。 由于我不知道您如何将根实例和EventList在一起,因此我假设您将其注册为全局组件。

该文件指出:

请注意,如果传递的 prop 是对象或数组,则它是通过引用传递的。 无论您使用哪种绑定类型,在子对象内部改变对象或数组本身都会影响父状态。

因此,当您将其作为 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>

这就是“道具”的用途:

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

如果您将对象/数组作为道具传递(您的events数据肯定会是什么),它会自动进行双向同步 - 在子级中更改事件,在父级中更改它们。

如果您通过道具传递简单的值(字符串、数字 - 例如只有 event.name),您必须明确使用.sync修饰符: http : .sync

this.$root.events

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM