Vue Router路由 (二)

61 阅读2分钟

一、上一节

Vue Router路由(一) - 掘金 (juejin.cn)

二、前置守卫

2.1 创建白名单

默认用户登录后才可以访问首页

image.png

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页面

20231225_232635.gif

三、后置守卫

3.1 效果演示

image.png

由登录页面跳转到首页后,将会触发afterEach事件

image.png

四、路由元信息

通过路由记录的meta属性可以定义路由的元信息,可以在路由中附加自定义的数据

4.1 创建元信息

为路由创建title属性,为了避免ts报错,需要额外声明title属性

image.png

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 读取元信息

image.png

4.3 效果演示

20231225_234800.gif

五、记录滚动位置

5.1 添加记录滚动位置逻辑

image.png

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 效果演示

当切换页面时,会记录上一次滚动条的位置,当返回该页面会重返此位置

20231226_221422.gif

六、动态路由