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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM