I have a single page application which consists of a:
A navigation component which contains a title and a menu A router-view I'd like each component being presented in the router view which correspond to a state in the router, to update the title of the navigation component. How to go about passing the parameters from the components in the router-view to the outer navigation component.
I'm using vue 2.0
You can just have a contain-all
Main
component which stores the current route, and pass it to the navigation and the router view component as the theirprop
s, then the situations are:Main
's stored route changes, the nav will rerender accordingly.watch
theprop
change,this.$router.push('/some/where')
when it changes.emit
s an event, along with the data (the route the user wants to go to), the parent receives the event, changes its stored route, which, according to the last 2 bullets, changes how nav and router view looks.The routes have to be part of the parent, since vue uses a parent-to-child-only one-way data flow. Children can't communicate with each other without help from their common parent unless we use some approach described in the last paragrath.
For details on how to implement parent-child data sharing, see doc.
Above is the simplest solution, which gets dirty quickly when your routes go nested. If so, you'll need a global event bus for non-parent-child data passing, or,
vuex
if you're looking at a large app and want your global states contained well.I would recommending Vuex for this:
https://github.com/vuejs/vuex
This way you can access your Vuex store in the main component and display its title:
Then you'd set up a mutation to update the title and call this wherever required in your components. Now as Vue is reactive the title within the nav component will update.
Below is an abbreviated example:
Vuex Store:
Your App Root:
Nav component:
Any other component which needs to update your title: