vue3 学习笔记02 – 配置路由router+导航守卫
路由的拦截及跳转
配置路由
- 安装路由库
npm install vue-router@4
- 定义路由
- 创建index.ts文件(具体路径:src/router/index.ts)
// src/router/index.ts
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
export const routes: Array<RouteRecordRaw> = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/login/index.vue'),
},
{
path: '/',
name: 'Home',
component: () => import('@/views/home/index.vue'),
}
];
const router = createRouter({
history: createWebHashHistory(),
routes: routes as RouteRecordRaw[],
scrollBehavior: () => ({ left: 0, top: 0 })
});
export default router;
-
创建视图组件
- src/views/login/index.vue
<template> <button @click="goToHome">跳转到首页</button> </template> <script lang="ts" setup> import { useRouter } from 'vue-router' const router = useRouter() const goToHome = ()=>{ router.push('/') } </script>
- src/views/home/index.vue
<template> <button @click="goToHome">跳转到登录页</button> </template> <script lang="ts" setup> import { useRouter } from 'vue-router' const router = useRouter() const goToHome = ()=>{ router.push('/login') } </script>
-
在main.js中引入挂载路由
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
- App.vue
<script setup lang="ts">
</script>
<template>
<router-view></router-view>
</template>
<style>
</style>
导航守卫
如果已登录存在token,则直接跳转到指定页面,否则进入登录页
- src/permission/index.ts
import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const whiteList = ['/login']
NProgress.configure({ showSpinner: false }) // 进度条
router.beforeEach(async (to, form, next) => {
NProgress.start()
if (存在token) {
if (to.path == '/login') {
next()
NProgress.done()
} else {
try{
next()
NProgress.done()
} catch (error) {
next(`/login`)
NProgress.done()
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
NProgress.done()
} else {
next(`/login`)
NProgress.done()
}
}
})