zoukankan      html  css  js  c++  java
  • Vue.js中,如何自己维护路由跳转记录?

    在Vue的项目中,如果我们想要做返回、回退操作时,一般会调用router.go(n)这个api,但是实际操作中,使用这个api有风险,就是会让用户跳出当前应用,因为它记录的是浏览器的访问记录,而不是你当前应用的访问记录,这是非常可怕的事情。

    解决方案就是,我们自己来维护一份history跳转记录。

    案例与使用场景

    代码地址:https://github.com/dora-zc/mini-vue-mall

    这是一个基于Vue.js的小型商城案例,应用场景:

    1. 自己实现一个Vue插件src/utils/history.js,通过堆栈的方式维护页面跳转的历史记录,控制返回跳转
    2. 点击返回按钮是出栈操作
    3. 在全局路由router.js 中,实例化路由前,通过原型扩展router的back()方法
    4. 在全局afterEach中存放历史记录

    代码实现

    实现history插件,维护历史记录

    // src/utils/history.js
    
    const History = {
        _history: [], // 历史记录堆栈
        install(Vue) {
            // 提供Vue插件所需安装方法
            Object.defineProperty(Vue.prototype, '$routerHistory', {
                get() {
                    return History;
                }
            })
        },
        push(path) { // 入栈
            this._history.push(path);
        },
        pop() {
            this._history.pop();
        },
        canBack(){
            return this._history.length > 1;
        }
    
    }
    export default History;
    

    在路由实例化之前,扩展back()方法

    // src/router.js
    
    import Vue from 'vue'
    import Router from 'vue-router'
    import History from './utils/history';
    
    Vue.use(Router);
    Vue.use(History);
    
    // 实例化之前,扩展Router
    Router.prototype.goBack = function () {
      this.isBack = true;
      this.back();
    }
    

    在路由全局afterEach中记录跳转历史

    // src/router.js
    
    // afterEach记录历史记录
    router.afterEach((to, from) => {
      if (router.isBack) {
        // 后退
        History.pop();
        router.isBack = false;
        router.transitionName = 'route-back';
      } else {
        History.push(to.path);
        router.transitionName = 'route-forward';
      }
    })
    

    在公用Header组件中使用

    // Hearder.vue
    
    <template>
      <div class="header">
        <h1>{{title}}</h1>
        <i v-if="$routerHistory.canBack()" @click="back"></i>
        <div class="extend">
          <slot></slot>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      props: {
        title: {
          type: String,
          default: ""
        }
      },
      methods: {
        back() {
          this.$router.goBack();
        }
      }
    };
    </script>
    

    完整代码请查看:https://github.com/dora-zc/mini-vue-mall

  • 相关阅读:
    梯度方向问题
    switchsharp
    R语言学习笔记:sort、rank、order、arrange排序函数
    R语言学习笔记:choose、factorial、combn排列组合函数
    MySQL学习笔记:少用Null
    Oracle学习笔记:11g服务介绍及哪些服务必须开启?
    GreenPlum学习笔记:create or replace function创建函数
    Python学习笔记:出生日期转化为年龄
    Python学习笔记:import sys模块(argv、path、platform、exit)
    Oracle学习笔记:wm_concat函数合并字段
  • 原文地址:https://www.cnblogs.com/dora-zc/p/10888071.html
Copyright © 2011-2022 走看看