模拟浏览器路由栈,使用自己的路由控制返回

638 阅读1分钟

1. 路由层级太深,返回不好控制

由于页面是可以一直下钻,在页面中又有时间选择页,更多展示的列表页,这个时候浏览器默认的路由栈不好控制返回,在头部的返回会出现混乱 先说一下自己的实现思想:使用栈的操作---后进先出,因为在js中没有栈这种数据结构,所以我用数组,也可以使用map对象。首先这个栈的操作要在整个工程中,所以我使用mobx作为状态管理的工具。 把整个的图画出来,剩下的就是边界值的处理。大体的就是这样操作了。

/**
 * @Author: visupervi
 * @Date: 11/26/20 2:06 PM
 * @return:
 * @Description 封装路由存储对象,使用js中的栈操作
 */
class RouterStore {
  // 初始化栈
  constructor(appStore) {
    appStore.routerStack = this.routerStack;
    appStore.pushStackHandler = this.pushStackHandler;
    appStore.popStackHandler = this.popStackHandler;
    appStore.count = this.count;
    appStore.isBack = this.isBack;
  }

  @observable routerStack = [];
  @observable count = 0;
  @observable isBack = false;

  // 入栈操作
  @action
  pushStackHandler(obj) {
    this.routerStack[this.count] = obj;
    console.log("this.routerStack", this.routerStack);
    ++this.count;
    return this.routerStack;

  }

  // 出栈操作
  /**
   * @Author: visupervi
   * @Date: 11/27/20 4:37 PM
   * @return:
   * @Description 返回上一页,栈要返回上一级记录
   */
  @action
  popStackHandler() {
    let tmp;
    if (this.count === 0) return null;
    if (this.count >= 2) {
      tmp = this.routerStack[this.count - 2];
      this.routerStack.splice(this.count - 1,1);
      if (this.count === 2) {
        this.routerStack.splice(1,1) ;
        this.count = 1;
        // return;
      }
    } else {
      tmp = this.routerStack[this.count - 1];
      this.routerStack.splice(1,1);
      this.count = 1;
      // return;
    }
    if(this.count > 1 ) --this.count;
    return tmp;
  }
}

我这样写是把前进去掉了,这样自定义栈中保留的是最新的记录。