vue + elementUi 导航组件,在进入子路由时怎样保持导航的激活状态?

<el-menu :default-active="$route.path" :router="true" class="el-menu-demo" mode="horizontal" @select="handleSelect">
    <el-menu-item index="/">
        <router-link to="/">首页</router-link>
    </el-menu-item>
    <el-menu-item index="/experience">
        <router-link to='/experience'>xxx</router-link>
    </el-menu-item>
    <el-menu-item index="/product">
        <router-link to='/product'>xx</router-link>
    </el-menu-item>
    <el-menu-item index="/agent">
        <router-link to='/agent'>xxx</router-link>
    </el-menu-item>
    <el-menu-item index="/share">
        <router-link to='/share'>xxxx</router-link>
    </el-menu-item>
</el-menu>
    export default {
        name: 'navbar',
        data: function() {
            return {
                activeIndex: '/',
            };
        },
        created:function(){
            this.defaultIdex()
        },
        methods: {
            handleSelect(key, keyPath) {
                //console.log(key, keyPath);
            },
            defaultIdex(){
                let path = this.$route.path;
                console.log(this.$route.matched[1].path);
            }
        },
        beforeUpdate:function(){
            return{
                activeIndex:this.$route.matched[1].path
            }
        }
    }

目前的效果是,点击导航跳转到另一个页面然后刷新可以保持激活状态。但是无法实现各自的子页面也保持导航的激活。不知道有什么方法,可以监听路由的变化,实现子路由也能配备到它父级的路由并且给导航加上激活状态。在element ui的文档中找不到可以实现的办法,希望各位大佬可以指点迷津!

阅读 11.2k
2 个回答
beforeUpdate:function(){
    return{
        activeIndex:this.$route.matched[1].path
    }
}

这是个比较明显的错误,改成

beforeUpdate:function(){
    this.activeIndex = this.$route.matched[1].path
}

没看到你代码里哪儿用到了这个变量,猜想你可能是用activeIndex来控制父菜单的激活状态,因为赋值操作不对所以在beforeUpdate的时候没有被改变,引起了你所说的问题吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题