返回按钮状态⾃动判断: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;}