Search code examples
javascriptroutervue-routervue.jsvuex

How to access a property of Vue object declared on a lower (parent) level?


In my index.js I have a Vue object that declares a router and renders the holder for all the pages.

const app = new Vue({ 
  ..., 
  render: _ => _(App),
  router, 
  ..., 
  el: "#app-base"});

In the page renderer I have components that sequentially have their subcomponents etc. Now I'd like to access the router instance declared on the outmost level and operate on it in the context of one of the toppy subcomponents.

How can I achieve that?

It doesn't exist in the context as is. Do I need to pass it up the tree somehow? What would be a good way to do that? Should I avoid the need to access bottomly declared instances in the topply working components?


Solution

  • Vue allows you to access and modify route at vue component level using this.$route variable.

    However this can be centralised by having generalised methods to modify route at root level component and whenever need to change from child components, call this root level method using vue-events.


    One can not access data of parent in child directly(there are ways, but not recommended), but one can call the method of parent using $emit, see this fiddle. In vue it is props down, event up for parent child communication