Vue.js - access data from root instance within component

前端 未结 2 1022
野性不改
野性不改 2020-12-18 21:00

This seems like a fairly basic question but I can\'t seem to find a definitive (or even working) answer.

I have my root instance:

var vm = new Vue({
         


        
2条回答
  •  生来不讨喜
    2020-12-18 21:16

    Using props, you can easily pass the same data from parent to children. Since I don't know how you linked the root instance and the EventList together, I'm going to assume you registered it as a global component.

    The documentation states:

    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.

    So you will be using the same object throughout all your components when you pass it as a 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();
    
    }
    
    });
    

    EventList:

    var EventsList = Vue.extend({
    
    template: '
    • {{ event.title }}

      {{ event.body }}

    ', 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);

    In the root vue instance template, you can pass the root vue instances events as a property called events in the child component:

提交回复
热议问题