这里的功能的是在浏览器的刷新时判断路由从而显示子导航栏。
可是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);
});
},
}
如果要实现这个功能,应该怎么做?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
試了下發現針對組件的鉤子才能這樣使用 (
beforeRouteEnter)...看了下源碼,
beforeEach會建立組件前先跑,所以沒辦法這樣搞,我這邊另外想個解決辦法是利用$route的meta,情況會比較簡單jsFiddle
我也遇到这个问题,试了很多遍,结论是只有在路由变化的时候才能触发
我的解决方案是在App.vue(根组件?) 中beforeCreate钩子中再写一遍...
改为
afterEach再看呢?其实这里可以直接在
created里写这个逻辑就是了。如果是多个地方都用,可以写一个 mixins. 这也避免了使用 bus 这种东西。更简单的方式,则是直接在模板里写逻辑判断就是了
其实定义路由时设置 name 属性并在其他地方做判断处理更好一些,这样即使 path 路径变了也不会有影响: