这是我参与「第五届青训营 」伴学笔记创作活动的第 N 天 #青训营笔记
VUE3的路由配置和VUE2有了很大的改动
注意:路径的“@”等同于"/src"!
'@/router'等同于'/src/router'
这样配置很方便对叭,可以去找看看vite的配置相关的文章哦
//main.ts
import router from '@/router';
.....
app.use(router)
//router文件夹内的index.ts
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
export const constantRoutes: RouteRecordRaw[] = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: () => import('@/views/login/index.vue'),
meta: { hidden: true }
},
//有错误页面就可以在import那里导入
// {
// path: '/404',
// component: () => import('@/views/error-page/404.vue'),
// meta: { hidden: true }
// },
//登录进去后的界面
// {
// path: '/home',
// component: () => import('@/views/home/index.vue')
// redirect: '/welcome'
// children: [
// {
// path: '/welcome',
// component: () => import('@/views/welcome/index.vue'),
// name: 'welcome',
// meta: { title: 'welcomepage', icon: 'welcomepage' }
// },
// {
// path: '401',
// component: () => import('@/views/error-page/401.vue'),
// meta: { hidden: true }
// }
// ]
// }
]
// 创建路由
const router = createRouter({
history: createWebHashHistory(),
routes: constantRoutes as RouteRecordRaw[],
// 刷新时,滚动条位置还原
scrollBehavior: () => ({ left: 0, top: 0 })
});
//导出路由
export default router;
二、路由使用
import router from '@/router'
router.push('/home')
三、路由解析(依据上面代码块)
1.path后设置的内容就是会出现在这个部分的内容(例如设置了path:'/home') http://localhost:3000/#/home 在这个网址下就是你的component后动态引入的组件内容了
2.component顾名思义,动态引入组件,在xxx处(()=>{xxx})填写组件的路径
3.redirect就是重定向,下面代码输入http://localhost:3000/#/ 就会被重定向到http://localhost:3000/#/login
{
path: '/',
redirect: '/login'
},
4.使用creatrouter创建一个对象保存在router里
const router = createRouter({
//history后面跟的是路由模式,案例用的是hash路由
//如果要是history路由的话,history: createWebHistory(import.meta.env.VITE_BASE_URL as string)
history: createWebHashHistory(),
routes: constantRoutes as RouteRecordRaw[],
// 刷新时,滚动条位置还原
scrollBehavior: () => ({ left: 0, top: 0 })
});
5.meta这个属性,就是相当于一个背在路由上的一个小背包,比如像下面的/welcome这个路由上,背上了"title","icon"的属性。然后可以通过 meta.tile 或 meta.icon 这样去提取出这个属性,去用它。
{
path: '/welcome',
component: () => import('@/views/welcome/index.vue'),
name: 'welcome',
meta: { title: 'welcomepage', icon: 'welcomepage' }
},
再往下是一个使用这个去修改网页标题的例子:
router.beforeEach((to,from,next)=>{
// 根据路由元信息设置文档标题
window.document.title = to.meta.title || admin next()
})
在vue3+TS体系中,都需要时刻注意创建的对象的类型,特别是在导入使用某些别人的库里面的对象的时候,都要在解构导入你需要使用的对象的同时导入他对应的类型。
//RouteRecordRaw就是类型
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';