user2353003
user2353003

Reputation: 542

Detect entry to parent component from child component Vue

I'm trying to find a way to detect when I have entered the parent component from child component. Since the parent component is already loaded when accessing the child, I cannot use the mounted() nor the created() life-cycle hook when entering back into the parent component.

Below code is an example of how my routes are layed out. When I navigate back to '/foo' from '/foo/bar', how can I detect that in the Foo component?

const routes = [
  { path: '/foo', component: Foo, 
  children: [
    { path: 'bar', component: Bar }
  ]}
]

Upvotes: 0

Views: 493

Answers (1)

Radu Diță
Radu Diță

Reputation: 14171

You can use navigation guard to get the previous route and do your check.

In your parent component you can add this:

beforeRouteEnter (to, from, next) {
 // here you can save to and check it in mounted for instance
 // call next and pass a callback to access the component when it is ready
 next(parentComp => {
   parentComp.navigatedFrom = from
 })
},

And then you can access navigatedFrom from inside your parent component.

Upvotes: 1

Related Questions