首页 > 解决方案 > 从子组件Vue检测到父组件的条目

问题描述

我试图找到一种方法来检测我何时从子组件进入父组件。由于在访问子组件时已经加载了父组件,因此在返回父组件时我不能使用mounted() 和created() 生命周期钩子。

下面的代码是我的路线布局的示例。当我从“/foo/bar”导航回“/foo”时,如何在 Foo 组件中检测到它?

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

标签: vue.jsvuejs2vue-componentvuexvue-router

解决方案


您可以使用导航守卫来获取先前的路线并进行检查。

在您的父组件中,您可以添加以下内容:

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
 })
},

然后你可以navigatedFrom从你的父组件内部访问。


推荐阅读