項目基于element-UI開發。頁面左側菜單控制右半部分内容顯示,但是設計稿上有幾個差異較大的頁面需要共用一個路由,高亮顯示菜單。
網上搜尋一番後決定采取query傳參的方式來在同一個路由上切換顯示不同頁面。
處理方法
- 頁面内監聽路由變化
watch: {
$route(to, from) {
// 擷取query中的參數
if (to.query.param1) {
this.param1 = to.query.param1
}
},
},
- methods跳轉方法修改
methods: {
...
edit(id) {
this.$router.push({ path: '/xxx/xxx', query: { id: id } })
},
...
}
效果->路由發生改變并跳轉到了目前頁面,同時頁面左側菜單高亮保持不變,資料進行了重新加載
可能遇到的問題
跳轉目前路由可能遇到如下錯誤
message: "Navigating to current location (XXX) is not allowed"
此時在src/router/index.js裡導入router的後面追加如下方法即可
import VueRouter from 'vue-router'
...
// fix Navigating to current location
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}