vue-router 的钩子在浏览器刷新后的事件监听应该放在哪个生命周期中?

这里的功能的是在浏览器的刷新时判断路由从而显示子导航栏。
可是bus.$on()事件并没有监听到,我感觉是因为我放置的生命周期不正确,反正几个生命周期除了destroyed我都试过了。。是不是我的思路有问题?

// router.js
// 页面刷新判断是否需要展示子导航
router.beforeEach((to, from, next) => {
  const pathTo = to.path;
  if (pathTo.match('/userManage')) {
    bus.$emit('showChildNav', 'user');
  } else if (pathTo.match('/contentManage')) {
    bus.$emit('showChildNav', 'content');
  }
  next();
});

// header.vue
export default {
  data () { ... },
  method: {
    showChild(type) {
      // this.navChild.concat(this.userManage); 为什么不生效
      if (type === 'user') {
        this.$set(this, 'navChild', this.userManage);
      } else if (type === 'content') {
        this.$set(this, 'navChild', this.contentManage);
      }
      this.secondNav = true;
    },
  },
  created() {
    bus.$on('showChildNav', (type) => {
      console.log('12213', type);
      this.showChild(type);
    });
  },
}

如果要实现这个功能,应该怎么做?

阅读 7.7k
3 个回答

試了下發現針對組件的鉤子才能這樣使用 (beforeRouteEnter)...
看了下源碼,beforeEach 會建立組件前先跑,所以沒辦法這樣搞,我這邊另外想個解決辦法是利用 $routemeta,情況會比較簡單

jsFiddle

新手上路,请多包涵

我也遇到这个问题,试了很多遍,结论是只有在路由变化的时候才能触发

我的解决方案是在App.vue(根组件?) 中beforeCreate钩子中再写一遍...

改为 afterEach 再看呢?
其实这里可以直接在 created 里写这个逻辑就是了。如果是多个地方都用,可以写一个 mixins. 这也避免了使用 bus 这种东西。

更简单的方式,则是直接在模板里写逻辑判断就是了

<div v-if="$route.path.match('/userManage')"></div>
<div v-if="$route.path.match('/contentManage')"></div>

其实定义路由时设置 name 属性并在其他地方做判断处理更好一些,这样即使 path 路径变了也不会有影响:

<div v-if="$route.name === 'userManage'">user</div>
<div v-if="$route.name === 'contentManage'">content</div>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题