vue3使⽤路由keep-alive和监听路由实现transition
随着vue3.0的发布,vue-router发布了4.0版本,很明了,提供了vue2路由到vue3的变化和写法指导。
vue2:
// transition
<transition name="van-fade">
<router-view />
</transition>
// keep-alive
<keep-alive>
<router-view v-if="this.$at.keepAlive"></router-view>
</keep-alive>
<keep-alive v-if="!this.$a.keepAlive"></keep-alive>
vue3:
<router-view v-slot="{ Component, route }">
<transition :name="ansitionName">
<keep-alive v-if="a.keepAlive">
<component :is="Component" />
</keep-alive>
<component :is="Component" v-else />
</transition>
</router-view>
需要使⽤ v-slot API来传⼊渲染的comp和route对象,⽽不再⽤this.$route
route.js写法⼤体没啥变化,写在最后的未匹配上路由的rediect,需要⽤正则来匹配
{transition用法搭配
// path: '/*',
path: '/:pathMatch(.*)*',
redirect: '/',
},
监听路由前进后退实现transtion的动画效果,查了许多资料都有点不太完善,有⽤数组存住history 每次⼿动push和pop然后⽐对的,有⽤storage的,有⽤⼦路由‘/’来对⽐的...
我的⽅式:
// route
router.beforeEach((to, from) => {
const toDepth = to.path.split('/').length;
const fromDepth = from.path.split('/').length;
toDepth > fromDepth ?
'slide-left' :
(to.path === store.state.pushPath ?
'slide-left' :
'slide-right');
});
// store
state: {
pushPath: '',
},
mutations: {
setPushPath(state, payload) {
state.pushPath = payload;
},
},
// util
export const push = (path: string, params?: Record<string, string | number>): void => {
storemit('setPushPath', path);
router.push({ path, params });
};
每次跳转使⽤⾃⼰简单封装的路由api,记录是前进还是后退。可还⾏
更新⼀下,这种 v-if 的⽅式,其实是有问题的,太久没登录博客了,项⽬⾥⾯已经发现了问题改⽤ include ⽅式,没有更新到⽂章。 原因是⼀旦有新打开的页⾯ , 会重新加载keep-alive组件 , 丢失所有缓存,导致回退页⾯的时候还是会⾛mounted,重新加载页⾯。
那么,就⽤ include 吧!
执⾏ watch 路由的操作,可以在app.vue⾥⾯写watch⽅式,也可以就在route⾥⾯的 beforeEach ⽅法⾥⾯去修改数组,通过store来绑定传值。
// route
router.beforeEach((to, from, next) => {
const toDepth = to.path.split('/').length;
const fromDepth = from.path.split('/').length;
// ansitionName =
/
/ toDepth > fromDepth ?
// 'van-slide-left' :
// (to.path === store.state.pushPath ?
// 'van-slide-left' :
// 'van-slide-right');
const isPush = toDepth > fromDepth || to.path === store.state.pushPath;
if (to.meta.keepAlive) {
storemit('addIncludes', to.name);
}
if (a.keepAlive && !isPush) {
storemit('minusIncludes', from.name);
}
next();
});
// store
state: {
pushPath: '',
include: []
},
mutations: {
setPushPath(state, payload) {
state.pushPath = payload;
},
addIncludes(state, payload) {
if (!state.include.includes(payload)) {
state.include.push(payload);
}
},
minusIncludes(state, payload) {
const index = state.include.indexOf(payload);
if (index !== -1) {
state.include.splice(index, 1);
}
},
},
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论