返回按鈕狀態⾃動判斷:history.length是不可靠的,它既包含了vue app路由記錄,也包括其餘 ⻚⾯的。能夠添加⼀個⾃定義的歷史記錄管理棧,建立./utils/history.jsvue
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從⽽管理記錄app
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.vuethis
<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; }