# VueRouter
# 1-构造一个路由对象
router.resolve
使用这个参数
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound/NotFound.vue')
}
const route = this.$router.resolve({
name: 'NotFound',
params: {
pathMatch: ['1', '33']
}
});
/*
{
"fullPath": "/1/33",
"hash": "",
"query": {},
"name": "NotFound",
"path": "/1/33",
"params": {
"pathMatch": [
"1",
"33"
]
},
"meta": {},
"href": "#/1/33"
}
*/
# 2-如何在路由参数变化时重新刷新
下面两个的区别
onBeforeRouteUpdate((to, from) => {
console.log('onBeforeRouteUpdate');
const id = Number(to.params.id);
getData(id).then((res) => {
tableData.value = res;
});
});
const route = useRoute();
watch(
() => route.params.id,
(newVal) => {
console.log('watch');
const id = Number(newVal);
getData(id).then((res) => {
tableData.value = res;
});
}
);
# 3-过渡动效
<RouterView v-slot="{ Component, route }">
<transition :name="route.meta.transition">
<component :is="Component"
test-prop="来自路由级的属性"></component>
</transition>
</RouterView>
过渡定义可以在路由配置中,也可以在导航守卫中
const _afterEach = (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
to.meta.transition = 'slide-right';
// from.meta.transition = 'leave-to-left';
};
router.afterEach(_afterEach);
{
path: 'users/:userid',
name: 'users',
meta: {
title: '用户-路由参数',
transition: 'slide-right'
},
component: () => import('@/views/Users/Users.vue')
}
# 4-检测导航故障
const navigationResult = await router.push('/my-profile')
if (navigationResult) {
// 导航被阻止
} else {
// 导航成功 (包括重新导航的情况)
this.isMenuOpen = false
}
# 5-全局导航故障
router.afterEach((to, from, failure) => {
if (failure) {
sendToAnalytics(to, from, failure)
}
})
# 6-添加动态路由
router.addRoute({ path: '/about', component: About })
# 添加嵌套路由
要将嵌套路由添加到现有的路由中,可以将路由的 name 作为第一个参数传递给 router.addRoute()
,这将有效地添加路由,就像通过 children
添加的一样:
const router = useRouter();
const addRoute = () => {
router.addRoute('layout', {
path: '/layout/child',
name: 'layout-child',
meta: {
title: '动态添加的路由'
},
component: () => import('./Child.vue')
});
router.replace({
name: 'layout-child'
});
};
# 7-查询现有路由
router.hasRoute()
检查路由是否存在。router.getRoutes()
获取一个包含所有路由记录的数组。