router/index.ts:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
component: () => import('../views/index/Home.vue'),
},
{
path: '/me/:id',
component: () => import('../views/me/Index.vue'),
beforeEnter: (to, from) => {
console.log('beforeEnter 路由独享的守卫')
return true
}
},
],
})
router.beforeEach((to, from) => {
console.log('beforeEach 全局前置守卫')
if (from.path === '/home') {
return true
} else {
return true
}
})
router.beforeResolve(async (to) => {
console.log('beforeResolve 全局解析守卫')
return true
})
router.afterEach((to, from) => {
console.log('afterEach 全局后置钩子')
})
export default router
me/Index.vue:
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router'
const router = useRouter()
onBeforeRouteUpdate(async (to, from) => {
console.log('onBeforeRouteUpdate 组件内')
})
onBeforeRouteLeave((to, from) => {
console.log('onBeforeRouteLeave 组件内')
})
const handleJumpPath = (path: any) => {
router.push(path)
}
onMounted(() => {})
</script>
<template>
<div>me</div>
<button @click="() => handleJumpPath('/me/2')">更新路由</button>
</template>
Home.vue:
<script setup>
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useSystem } from './config'
import { nanoid, customAlphabet } from 'nanoid'
import Header from './Header.tsx'
import { useMenuStore } from '../../stores/menu'
import './index.css'
const router = useRouter()
const route = useRoute()
const handleJumpPath = (path) => {
router.push(path)
}
onMounted(() => {
// const { service } = useSystem()
// service.chat.handleLoginOut()
let id1 = nanoid()
console.log(id1)
let customNanoid = customAlphabet('1234567890', 5)
let id2 = customNanoid()
console.log(id2)
const { handleGetMenuData } = useMenuStore()
let meunData = handleGetMenuData()
console.log('meunData', meunData)
})
</script>
<template>
<div>
<Header></Header>
<button @click="() => handleJumpPath('/me/1')">me</button>
<el-button>1</el-button>
</div>
</template>
参考链接
https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
人工智能学习网站