遇到需要切换页面显示,重新请求接口但是前端路由不变时的一种处理方法
项目基于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)
}
在基于Element-UI的Vue项目中,当需要在不改变前端路由的情况下切换页面内容并根据query参数加载不同数据时,可以采用监听路由变化的方式处理。通过在watch中捕获query参数并更新视图,同时在methods中使用$router.push方法传递query参数实现页面跳转。若遇到‘Navigating to current location’错误,可在VueRouter原型上修复push方法。这种方法允许在同一个路由下显示设计稿中差异较大的页面,并保持菜单高亮。
802

被折叠的 条评论
为什么被折叠?



