ant-vue之导航跳转(非点击导航事件)动态监听路由变化

在做导航时,vue-ant 导航点击事件框架交互是根据selected=['navitem']来进行的

绑定的selected每次点击更改navitem值即可,但是如果出现手动输入路径和在其它页面点击返回,路径变了,导航的事件和默认是不会发生变化的

开始考虑selected是数组,怀疑是因为数组操作数据不刷新,用this.$set

后来用computed接管 :selected=computedSelect =>  内部用状态管理接管 => return  this.$store.state.selected 然后用state 的mutation 方法全局改变(哪个页面用到哪个页面提交)

store.js
const _this = new Vue()
mutations: {
                fnselectedKeys(state,newNavStr){//更改selectedKeys
                    state.selectedKeys =[]
                    // state.selectedKeys[0] = newNavStr
                    _this.$set(state.selectedKeys,0,newNavStr)
                    // console.log(_this.$set)
                },}

nav.js

// selectedKeys(){//data内的数据不会自动更新
            //     return this.$store.state.selectedKeys
            // }

user.js

// 
navSelect(nav){
this.$store.commit('fnselectedKeys',nav)}

 

 后来发现vue不会动态获取到route.path

绕了一圈直接简化了方式:

1.写一个方法(也可以省略用路由名动态绑定路径更简洁):

2:监听路由的路径(不管手动输入还是返回还是其它页面的事件内跳转):只要有改变就会跳转并更改事件默认selected值

watch: {//动态监听路由变化 -以便动态更改导航背景色事件效果等
            '$route' (to, from) {
              // 对路由变化作出响应...
              console.log('to.path----',to.path)//跳转后路由
              console.log('from----',from)//跳转前路由
              this.navSelect(to.path)
            }
          },
<a-menu-item key="/Account"  @click='navSelect("/Account")'>
                                <router-link to="/Account">
                                    <a-icon type="reconciliation" />
                                    <span>系统管理</span>
                                </router-link>
                            </a-menu-item>
事件:
//导航点击
            navSelect(nav){
                this.$set(this.selectedKeys,0,nav)
                // this.$store.commit('fnselectedKeys',nav)
                // this.selectedKeys[0] = nav
            },

 

 

如果想要胜率第一步:

直接在key="路由路径" 基础上 添加监听路由即可,路由监听触发事件为重新赋值key即可

//wacth内:
this
.selectedKeys = [] this.selectedKeys.push('
to.path
')

 另外还有个小细节要注意:

如果在开发中经常保存自动刷新页面,导航默认选中背景色会出错,回到首页-实际页面不在首页,导致这个原因是watch并没有监测到路由发生变化了,路由沿用了mounted初始化时的首页,这时候只要在mounted挂载时初始化一次即可,(后面再刷新也不会再出现这种情况)

methods:{
initNavbar(){//初始化如果手动输入路由,其它路径事件对应到指定路由导航事件
                var initRouterPath = this.$route.path
                this.navSelect(initRouterPath)
}
}
mounted(){
this.initNavbar()
}

 

posted @ 2020-07-27 15:53  少哨兵  阅读(1304)  评论(0编辑  收藏  举报