0
votes

The basic setup of my little Vue app follows the basic Vue Cli 3 setup:

  • -main.js (= root)
  • -- App.vue
  • --- Navigation.vue (this one calls $root)

In main.js's created() there is this function to load the json for the navigation menu:

[...]
data() {
    return {
        navMainItems: null
        staticTestItems: [
            { "id": 0, "title": "test 1, "url": "/" },
            { "id": 1, "title": "test 2, "url": "/" }
        ]
    }
},
created() {
    axios.get('navigation/navAllItems.json')
        .then((response) => {
            this.navMainItems = response.data.navMainItems;
    [...]
}

which works fine. Now I would like to call that data from the Navigation.vue component using "this.$root":

data(){
  return {
    navItems: null,
    localStaticTestItems: this.$root.staticTestItems
  }
},
created() {
    // Check if static elements loaded
    console.log("sampleNavItems =", this.$root.sampleNavItems)
},
mounted(){
  // This fails, presumably because of asynchonicity
  // Can this be fixed?
  this.navItems = this.$root.navMainItems
}

While the static elements are loaded perfectly fine, the asynchronously loaded navItems do not update.

I am well aware of other approaches like "event bus", "props", or "VueX", but for not I would like to use the dialog with the $root component and learn how to react to asynchonicity - if that is at all possible in this scenario.

1

1 Answers

1
votes

I'm not 100% sure, but in your case making navItems in your child component a computed property might work:

  computed: {
    navItems() { return this.$root.navMainItems }
  }

Here's a fiddle with example: http://jsfiddle.net/eywraw8t/268423/