一、上一节
Vue Router路由(一) - 掘金 (juejin.cn)
二、前置守卫
2.1 创建白名单
默认用户登录后才可以访问首页
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
export const app = createApp(App)
const whileList = ["/"]
router.beforeEach((to,from,next)=>{
if(whileList.includes(to.path) || localStorage.getItem("token") ){
next()
}else{
next("/")
}
})
app.use(router)
app.mount('#app')
2.2 创建路由信息
有两个路由页面,/
为登录页面,只有登录后才可以访问首页/index
import { createRouter,createWebHistory,RouteRecordRaw } from "vue-router";
const routes:Array<RouteRecordRaw> = [{
path:"/",
component:()=>import("../components/Login.vue")
},{
path:"/index",
component:()=>import("../components/Index.vue")
}]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
2.3 创建登录页面
用户在登录后会将产生token,并存入localstorage
<template>
<p>这是登录界面</p>
<button @click="toIndex">登录,然后去首页</button>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter()
function toIndex(){
router.push("/index")
localStorage.setItem("token","1")
}
</script>
2.4 效果演示
当用户直接访问/index时,由于既没有token,也不存在于白名单中,拒绝访问;当成功登录后才可以进入index页面
三、后置守卫
3.1 效果演示
由登录页面跳转到首页后,将会触发afterEach事件
四、路由元信息
通过路由记录的meta属性可以定义路由的元信息,可以在路由中附加自定义的数据
4.1 创建元信息
为路由创建title属性,为了避免ts报错,需要额外声明title属性
import { createRouter,createWebHistory,RouteRecordRaw } from "vue-router";
declare module 'vue-router'{
interface RouterMeta{
title:string
}
}
const routes:Array<RouteRecordRaw> = [{
path:"/",
component:()=>import("../components/Login.vue"),
meta:{
title:"这是登录页面",
}
},{
path:"/index",
component:()=>import("../components/Index.vue"),
meta:{
title:"这是首页",
}
}]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
4.2 读取元信息
4.3 效果演示
五、记录滚动位置
5.1 添加记录滚动位置逻辑
import { createRouter,createWebHistory,RouteRecordRaw } from "vue-router";
declare module 'vue-router'{
interface RouterMeta{
transition:string
}
}
const routes:Array<RouteRecordRaw> = [{
path:"/",
component:()=>import("../components/Login.vue"),
meta:{
transition:"transition"
}
},{
path:"/index",
component:()=>import("../components/Index.vue"),
meta:{
transition:"transition"
}
}]
const router = createRouter({
history:createWebHistory(),
routes,
scrollBehavior:(to,from,savePosition)=>{
if(savePosition){
return savePosition
}else{
return{
top:0
}
}
}
})
export default router
5.2 效果演示
当切换页面时,会记录上一次滚动条的位置,当返回该页面会重返此位置