mock没接触过,现在跳过这部分看main.js App.vue其他内容
引入App.vue及router
<template>
<div id="app">
<router-view />
</div>
</template>
/router/index.js
{
path: '/',
component: Layout,
redirect: '/dashboard', //vue重定向 访问localhost:8000 会到 localhost:8000/dashboard
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: 'Dashboard', icon: 'dashboard' }
}]
},
路由
此处component和redirect children 的关系:
输入localhost:8000会默认进入dashboard界面,其过程为:
先加载component中的layout,在layout/index.vue中,引入了<app-main />
,appmain.vue中引入了<router-view :key="key" />
这个router-view会加载children中的component,这大概就叫‘嵌套视图’
理解来自:https://router.vuejs.org/zh/guide/essentials/nested-routes.html
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
// 当 /user/:id/profile 匹配成功
// UserProfile 将被渲染到 User 的 <router-view> 内部
path: 'profile',
component: UserProfile,
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 将被渲染到 User 的 <router-view> 内部
path: 'posts',
component: UserPosts,
},
],
},
]
meta
meta的定义:简单来说就是路由元信息,也就是每个路由身上携带的信息。
meta的作用:vue-router路由元信息说白了就是通过meta对象中的一些属性来判断当前路由是否需要进一步处理,如果需要处理,按照自己想要的效果进行处理即可
可以再meta里设置登录验证
meta keep-alive属性具有缓存作用见https://juejin.cn/post/7098605987925327902
scrollBehavior
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }), // y=0 顶部
routes: constantRoutes
// return 期望滚动到哪个的位置
})
scrollBehavior:使用前端路由,当切换到新路由时,想要页面滚到顶部,
或者是保持原先的滚动位置,就像重新加载页面那样。
vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。
https://v3.router.vuejs.org/zh/guide/advanced/scroll-behavior.html#%E5%BC%82%E6%AD%A5%E6%BB%9A%E5%8A%A8
router.matcher
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
此段代码略复杂。后续用到再研究更新
至此/router/index.js分析完毕