1

返回按钮状态⾃动判断:history.length是不可靠的,它既包含了vue app路由记录,也包括其他 ⻚⾯的。可以添加⼀个⾃定义的历史记录管理栈,创建./utils/history.js

const History = {
 _history: [], // 历史记录堆栈
 install(Vue) {
 // vue插件要求的安装⽅法
 Object.defineProperty(Vue.prototype, "$routerHistory", {
 get() {
 return History;
 }
 });
 },
 push(path) {
 // ⼊栈
 this._current += 1;
 this._history.push(path);
 },
 pop() {
 // 出栈
 this._current -= 1;
 return this._history.pop();
 },
 canBack() {
 return this._history.length > 1;
}
};
export default History;

router.js中引⼊,添加⼀个后退⽅法并监听afterEach从⽽管理记录

import History from "./utils/history";
Vue.use(History);
Router.prototype.goBack = function() {
 this.isBack = true;
 this.back();
};
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.vue

<i v-if="$routerHistory.canBack()"></i>
methods: {
 back() {this.$router.goBack();}
}

后退动画,App.vue

<transition :name="transitionName">
 <router-view class="child-view"/>
</transition>

data() {
 return {
 transitionName: 'route-forward'
 };
 },
 watch: {
 $route() {
 // 动态设置动画⽅式
 this.transitionName = this.$router.transitionName
 }
 },


/* ⻚⾯滑动动画 */
/* ⼊场前 */
.route-forward-enter {
 transform: translate3d(-100%, 0, 0);
}
.route-back-enter {
 transform: translate3d(100%, 0, 0);
}
/* 出场后 */
.route-forward-leave-to {
 transform: translate3d(100%, 0, 0);
}
.route-back-leave-to {
 transform: translate3d(-100%, 0, 0);
}
.route-forward-enter-active,
.route-forward-leave-active,
.route-back-enter-active,
.route-back-leave-active {
 transition: transform 0.3s;
}

HappyCodingTop
526 声望847 粉丝

Talk is cheap, show the code!!