在Vue的项目中,若是咱们想要作返回、回退操做时,通常会调用router.go(n)
这个api,可是实际操做中,使用这个api有风险,就是会让用户跳出当前应用,由于它记录的是浏览器的访问记录,而不是你当前应用的访问记录,这是很是可怕的事情。vue
解决方案就是,咱们本身来维护一份history跳转记录。git
代码地址:https://github.com/dora-zc/mini-vue-mallgithub
这是一个基于Vue.js的小型商城案例,应用场景:vue-router
src/utils/history.js
,经过堆栈的方式维护页面跳转的历史记录,控制返回跳转// 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;
// 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(); }
// 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'; } })
// 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-mallapi