vue中路由返回解决方案

390 阅读1分钟

项目中通过在query中添加from字段来进行路由返回控制,随着项目越来越复杂,多入口及其他项目调转过来, 使用from来控制路由返回变得越来越复杂,因此我们对路由返回进行优化

思路:

路由每次进入时将路由路由及参数存储在stroe中,点击返回时清除数组中最后一项,如果数组长度为0,则关闭当前页面,这样可以保证不管从哪个入口来的页面都可以正常返回,而不用写太多的if判断

  1. store中保存路由记录及参数

    state中初始化路由数据RouterArr

  2. 提交及删除路由

//添加路由记录
pushRouter(state,router) {
    if(state.routerArr.length&&state.routerArr[state.routerArr.length-1].path!=router.path){
      state.routerArr.push(router)
    }else if(state.routerArr.length==0){
      state.routerArr.push(router)
    }
}

//删除路由记录
popRouter(state,path) {
    if(path){
      let index = state.routerArr.findIndex(function(item){
        return item.path == path
      })
      state.routerArr.splice(index)
    }else{
      state.routerArr.pop()
    }
  },
  1. 在路由进入后将路由push进路由记录

router.afterEach((to,from)=> {
   store.commit('pushRouter',{path:to.path,query:to.query})
})

  1. 删除路由绑定到vue原型,方便调用

Vue.prototype.routerBack=(path)=>{
   let routerObj = _.cloneDeep(_.find(store.state.routerArr,{path:path}))
 store.commit('popRouter',path)
 //兼容多入口跳转
 if(store.state.routerArr.length&&!path){
   router.push(store.state.routerArr[store.state.routerArr.length-1])
 }else if(path&&routerObj){  
   router.push(routerObj) 
 }else{
   dtCloseApp() //
 }
}

  1. 使用
  • 在需要使用地方直接调用this.routerBack()