先上代码
<router-view v-slot="{ Component }">
<keep-alive>
<component :key="$route.name" :is="Component" v-if="$route.meta.keepAlive" />
</keep-alive>
<component :key="$route.name" :is="Component" v-if="!$route.meta.keepAlive" />
</router-view>
const routes = [
{
path: '/',
redirect: '/home',
},
// Home
{
path: '/home',
name: 'Home',
meta: {
keepAlive: true,
},
component: Home
},
// Detail
{
path: '/detail',
name: 'Detail',
meta: {
keepAlive: false,
},
component: () => import('@/views/detail/index.vue'),
},
...
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
vue2的keep-alive 参考
<keep-alive include="Home,Ranking">
<router-view />
</keep-alive>
vue3 使用注意点:
报错:parentComponent.ctx.deactivate is not a function :
需要在 <component :key="$route.name" ... />
keep-alive相关的钩子函数: activated / deactivated
https://v3.cn.vuejs.org/api/options-lifecycle-hooks.html#activated
onActivated(() => {
})
onDeactivated(() => {
})
vue3中 vue-router 的scrollBehavior变化
https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html
const router = createRouter({
history: createWebHashHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
if (to.name === 'Detail') {
return { x: 0, y: 0 };
}
return savedPosition;
}
});
改为:
const router = createRouter({
history: createWebHashHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
if (to.name === 'Detail') {
return { top: 0 };
}
return savedPosition;
}
});
vue3中 vue-router 的使用
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const { id } = route.query;
const clickToRouteDetail = (id) => {
router.push({
path: './detail',
query: {
id,
},
});
}