對于給app頁面切換時添加過渡效果胖腾,vue-router的官方文檔中也有案例(https://router.vuejs.org/zh-cn/advanced/transitions.html)宏粤。此例是結(jié)合app實際的頁面跳轉(zhuǎn)情況蹬叭,在官方案例的基礎(chǔ)上做的補充和調(diào)整。相關(guān)文件如下:
index.html
<body>
<div id="app">
<router-view></router-view>
</div>
</body>
main.js
new Vue({
router,
components: { App }
}).$mount('#app')
router配置
要實現(xiàn)頁面前進后臺動畫,首先必須知道頁面狀態(tài)(即是頁面是進入下一頁柠逞,還是后退),我們可以通過改寫router.go方法記錄回退狀態(tài)景馁,頁面如果需要回退時板壮,調(diào)用this.$router.go(-1),改寫代碼如下:
Router.prototype.go = function () {
this.isBack = true
window.history.go(-1)
}
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import App from '../App'
const Home = r => require.ensure([], () => r(require('../page/Home')), 'Home')
Vue.use(Router)
// 增強原方法:isBack作為標識來記錄前進后退
Router.prototype.go = function () {
this.isBack = true
window.history.go(-1)
}
let routes = [
{
path: '/',
component: App,
children: [
{
path: '',
redirect: '/home'
},
{
path: '/home',
name: 'home',
component: Home
}
]
}
]
export default new Router({
mode: 'history',
routes: routes,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
if (from.meta.keepAlive) {
from.meta.savedPosition = document.body.scrollTop
}
return { x: 0, y: to.meta.savedPosition || 0 }
}
}
})
App.vue
html代碼
<template>
<div>
<transition :name="transitionName" mode="out-in">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" class="child-view"></router-view>
</keep-alive>
</transition>
<transition :name="transitionName" mode="out-in">
<router-view v-if="!$route.meta.keepAlive" class="child-view"></router-view>
</transition>
</div>
</template>
js代碼
export default {
data () {
return {
transitionName: 'slide-left'
}
},
beforeRouteUpdate (to, from, next) {
// 如果isBack為true時合住,證明是用戶點擊了回退绰精,執(zhí)行slide-right動畫
let isBack = this.$router.isBack
if (isBack) {
this.transitionName = 'slide-right'
} else {
this.transitionName = 'slide-left'
}
// 做完回退動畫后撒璧,要設(shè)置成前進動畫,否則下次打開頁面動畫將還是回退
this.$router.isBack = false
next()
}
}
css代碼
.child-view {
position: absolute;
width:100%;
transition: all .4s cubic-bezier(.55,0,.1,1);
}
.slide-left-enter, .slide-right-leave-active {
opacity: 0;
-webkit-transform: translate(50px, 0);
transform: translate(50px, 0);
}
.slide-left-leave-active, .slide-right-enter {
opacity: 0;
-webkit-transform: translate(-50px, 0);
transform: translate(-50px, 0);
}
1渴埂G溆!!阱表!還沒有結(jié)束5钊纭!W钆馈涉馁!
頁面跳轉(zhuǎn)時回退除了this.$router.go(-1)以外,還可以通過this.$router.replace('上一個頁面的路由地址')的方式返回前一個頁面爱致,那接下來要怎么操作呢烤送?改寫router.go方法已經(jīng)不夠用啦,那就看下去咯
需求場景:A頁面進入B頁面糠悯,B頁面點擊完成以后返回前一頁帮坚,并且B頁面需要傳參給A頁面,B頁面點擊完成的代碼如下:
rightClick () {
this.$router.replace({
path: '/A',
query: {name: '傳了個name'}
})
}
那么互艾,在離開B頁面之前试和,需要在B頁面通過beforeRouteLeave來監(jiān)聽路由變化:
beforeRouteLeave (to, from, next) {
// 告訴路由要使用回退動畫
this.$router.isBack = true
next()
}
YOYO,到這里纫普,就全部都OK啦阅悍!