Search code examples
vue.jsvue-componentvuex

VueJS access child component's data from parent


I'm using the vue-cli scaffold for webpack

My Vue component structure/heirarchy currently looks like the following:

  • App
    • PDF Template
      • Background
      • Dynamic Template Image
      • Static Template Image
      • Markdown

At the app level, I want a vuejs component method that can aggregate all of the child component's data into a single JSON object that can be sent off to the server.

Is there a way to access child component's data? Specifically, multiple layers deep?

If not, what is the best practice for passing down oberservable data/parameters, so that when it's modified by child components I have access to the new values? I'm trying to avoid hard dependencies between components, so as of right now, the only thing passed using component attributes are initialization values.

UPDATE:

Solid answers. Resources I found helpful after reviewing both answers:


Solution

  • For this kind of structure It's good to have some kind of Store.

    VueJS provide solution for that, and It's called Vuex.If you are not ready to go with Vuex, you can create your own simple store.

    Let's try with this

    MarkdownStore.js

    export default {
    
     data: {
       items: []
     },
    
     // Methods that you need, for e.g fetching data from server etc.
    
     fetchData() {
       // fetch logic
     }
    
    }
    

    And now you can use those data everywhere, with importing this Store file

    HomeView.vue

    import MarkdownStore from '../stores/MarkdownStore'
    
    export default {
    
     data() {
       sharedItems: MarkdownStore.data
     },
    
     created() {
       MarkdownStore.fetchData()
     }
    
    }
    

    So that's the basic flow that you could use, If you dont' want to go with Vuex.