官方文档:https://router.vuejs.org/zh/installation.html
1.安装(vue3安装vue-router@4,vue2请查看文档安装 | Vue Router)
npm install vue-router@4
2.在src目录下创建router/index.js文件
3.创建router实例
import { createWebHashHistory, createRouter } from 'vue-router'
import HomeView from './HomeView.vue'
import AboutView from './AboutView.vue'
const routes = [
{ path: '/', component: HomeView },
{ path: '/about', component: AboutView },
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
4.在main.js中挂载router实例
/** @format */
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router).use(ElementPlus)
app.mount('#app')
5.在APP.vue中配置路由出口(如果是嵌套路由,一样需要配置路由出口)
<!-- @format -->
<script setup>
import { RouterView } from 'vue-router'
</script>
<template>
<RouterView></RouterView>
</template>
<style scoped></style>
6.配置路由守卫(在路由跳转之前进行判断)
每个守卫方法接收两个参数:
to
: 即将要进入的路由
from
: 当前导航正要离开的路由
//路由守卫
router.beforeEach((to, from) => {
const token = localStorage.getItem('login_token')
//非登陆且页面token不存在,跳转登陆页面
if (!token && to.path !== '/login') {
return '/login'
} else if (token && to.path === '/login') {
return '/'
} else {
return true
}
})