feat: RouterStack
Some checks failed
CI / cache-and-install (push) Failing after 1m1s

This commit is contained in:
严浩
2024-08-08 15:13:35 +08:00
parent 5c11b15c1b
commit 2798254dab
18 changed files with 272 additions and 308 deletions

View File

@ -1,89 +1,5 @@
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script>
<script setup lang="ts"></script>
<template>
<header>
<img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />
<div class="wrapper">
<HelloWorld msg="You did it!" />
<nav>
<RouterLink :to="{ name: 'IndexPage' }">Home</RouterLink>
<RouterLink :to="{ name: 'AboutPage' }">About</RouterLink>
</nav>
</div>
</header>
<nav>
<button @click="$router.push({ name: 'AboutPage' })">AboutButtonPush</button>
</nav>
<RouterView />
</template>
<style scoped>
header {
line-height: 1.5;
max-height: 100vh;
}
.logo {
display: block;
margin: 0 auto 2rem;
}
nav {
width: 100%;
font-size: 12px;
text-align: center;
margin-top: 2rem;
}
nav a.router-link-exact-active {
color: var(--color-text);
}
nav a.router-link-exact-active:hover {
background-color: transparent;
}
nav a {
display: inline-block;
padding: 0 1rem;
border-left: 1px solid var(--color-border);
}
nav a:first-of-type {
border: 0;
}
@media (min-width: 1024px) {
header {
display: flex;
place-items: center;
padding-right: calc(var(--section-gap) / 2);
}
.logo {
margin: 0 2rem 0 0;
}
header .wrapper {
display: flex;
place-items: flex-start;
flex-wrap: wrap;
}
nav {
text-align: left;
margin-left: -1rem;
font-size: 1rem;
padding: 1rem 0;
margin-top: 1rem;
}
}
</style>

View File

@ -1,88 +0,0 @@
<script setup lang="ts">
import WelcomeItem from './WelcomeItem.vue'
import DocumentationIcon from './icons/IconDocumentation.vue'
import ToolingIcon from './icons/IconTooling.vue'
import EcosystemIcon from './icons/IconEcosystem.vue'
import CommunityIcon from './icons/IconCommunity.vue'
import SupportIcon from './icons/IconSupport.vue'
</script>
<template>
<WelcomeItem>
<template #icon>
<DocumentationIcon />
</template>
<template #heading>Documentation</template>
Vues
<a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
provides you with all information you need to get started.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<ToolingIcon />
</template>
<template #heading>Tooling</template>
This project is served and bundled with
<a href="https://vitejs.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
recommended IDE setup is
<a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a> +
<a href="https://github.com/johnsoncodehk/volar" target="_blank" rel="noopener">Volar</a>. If
you need to test your components and web pages, check out
<a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a> and
<a href="https://on.cypress.io/component" target="_blank" rel="noopener"
>Cypress Component Testing</a
>.
<br />
More instructions are available in <code>README.md</code>.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<EcosystemIcon />
</template>
<template #heading>Ecosystem</template>
Get official tools and libraries for your project:
<a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
<a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
<a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
<a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
you need more resources, we suggest paying
<a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
a visit.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<CommunityIcon />
</template>
<template #heading>Community</template>
Got stuck? Ask your question on
<a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>, our official
Discord server, or
<a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
>StackOverflow</a
>. You should also subscribe to
<a href="https://news.vuejs.org" target="_blank" rel="noopener">our mailing list</a> and follow
the official
<a href="https://twitter.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
twitter account for latest news in the Vue world.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<SupportIcon />
</template>
<template #heading>Support Vue</template>
As an independent project, Vue relies on community backing for its sustainability. You can help
us by
<a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
</WelcomeItem>
</template>

View File

@ -1,87 +0,0 @@
<template>
<div class="item">
<i>
<slot name="icon"></slot>
</i>
<div class="details">
<h3>
<slot name="heading"></slot>
</h3>
<slot></slot>
</div>
</div>
</template>
<style scoped>
.item {
margin-top: 2rem;
display: flex;
position: relative;
}
.details {
flex: 1;
margin-left: 1rem;
}
i {
display: flex;
place-items: center;
place-content: center;
width: 32px;
height: 32px;
color: var(--color-text);
}
h3 {
font-size: 1.2rem;
font-weight: 500;
margin-bottom: 0.4rem;
color: var(--color-heading);
}
@media (min-width: 1024px) {
.item {
margin-top: 0;
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
}
i {
top: calc(50% - 25px);
left: -26px;
position: absolute;
border: 1px solid var(--color-border);
background: var(--color-background);
border-radius: 8px;
width: 50px;
height: 50px;
}
.item:before {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
bottom: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:after {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
top: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:first-of-type:before {
display: none;
}
.item:last-of-type:after {
display: none;
}
}
</style>

View File

@ -5,11 +5,9 @@ import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import { router } from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
createApp(App)
.use(createPinia())
.use(router)
.mount('#app')

View File

@ -1,15 +0,0 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>

View File

@ -1,12 +1,13 @@
<script setup lang="ts">
import TheWelcome from '../components/TheWelcome.vue'
definePage({
alias: '/',
alias: '/'
})
</script>
<template>
<main>
<TheWelcome />
</main>
<div class="flex gap-2">
<t-button @click="$router.push({ name: 'Page1' })">ToPage1</t-button>
<t-button @click="$router.push({ name: 'Page2' })">ToPage2</t-button>
<t-button @click="$router.push({ name: 'Page3' })">ToPage3</t-button>
</div>
</template>

10
src/pages/page-1.vue Normal file
View File

@ -0,0 +1,10 @@
<template>
<div>
<t-button @click="$router.back()">back()</t-button>
</div>
<div class="h-2" />
<div class="flex gap-2">
<t-button @click="$router.push({ name: 'Page2' })">ToPage2</t-button>
<t-button @click="$router.replace({ name: 'Page2' })">ReplaceToPage2</t-button>
</div>
</template>

31
src/pages/page-2.vue Normal file
View File

@ -0,0 +1,31 @@
<template>
<!-- <VanButton @click="backToHome">Back to Home</VanButton> -->
<div class="flex gap-2">
<t-button @click="$router.go(-1)">go(-1)</t-button>
<t-button @click="$router.go(-2)">go(-2)</t-button>
</div>
</template>
<script setup lang="ts">
import { router } from '@/router';
function backToHome() {
console.log('router.options.history.state.back :>> ', router.options.history.state.back);
const backToName = 'IndexPage';
console.log('backToName :>> ', backToName);
let backCount = 0;
/* for (let i = router.stack.currentStackIndex - 1; i >= 0; i--) {
if (router.stack.list[i].name === backToName) {
backCount = router.stack.currentStackIndex - i;
break;
}
} */
console.log('backCount :>> ', backCount);
}
onMounted(() => {
// console.log('router.currentRoute.value.from :>> ', router.currentRoute.value.from);
// backToHome()
})
</script>

1
src/pages/page-3.vue Normal file
View File

@ -0,0 +1 @@
<template>page-3</template>

26
src/router/guard/index.ts Normal file
View File

@ -0,0 +1,26 @@
import NProgress from 'nprogress'
import type { Router } from 'vue-router'
import { createLogGuard, createStackGuard } from './log-guard'
// Don't change the order of creation
export function setupRouterGuard(router: Router) {
createProgressGuard(router)
createLogGuard(router)
createStackGuard(router)
router.onError((error) => {
console.debug('🚨 [router error]: ', error)
})
}
export function createProgressGuard(router: Router) {
router.beforeEach(() => {
NProgress.start()
})
router.afterEach(() => {
NProgress.done()
})
}

View File

@ -0,0 +1,147 @@
import { START_LOCATION } from 'vue-router'
import type { RouteLocationNormalized, Router } from 'vue-router'
export function createLogGuard(router: Router) {
router.beforeEach(async (to, from, next) => {
console.debug(
'🚗 ====================',
`[beforeEach]`,
`[${from === START_LOCATION ? 'START_LOCATION' : String(from.name || '')}]`,
`-> [${String(to.name)}].`,
'===================='
)
next()
})
router.afterEach(async (to, from, failure) => {
console.debug(
'🚗 ====================',
` [afterEach]`,
`[${from === START_LOCATION ? 'START_LOCATION' : String(from.name || '')}]`,
`-> [${String(to.name)}].`,
'==================== 🚗🚗🚗',
`failure: `,
failure
)
})
}
export function createStackGuard(router: Router) {
// const stack = router.stack = { /* list: [] as RouteLocationNormalized[], */ currentStackIndex: 0 }
let startPosition = -1
let curPosition = -1
// if ($__DEV__) Object.assign(window, { stack })
const _routerHistory = router.options.history
/* window.addEventListener('beforeunload', function (event) {
console.debug("🚥", '[onbeforeunload]', "event :>> ", event);
const confirmationMessage = "\\o/";
(event || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
}) */
_routerHistory.listen((to, from, info) => {
console.debug('🚥 listen', ':')
console.debug('🚥 listen', 'from :>> ', from)
console.debug('🚥 listen', 'to :>> ', to) // TODO: 在afterEach那里核对
console.debug('🚥 listen', 'info :>> ', info)
// lastNavigationInfo.lastInfo = info;
});
// #############################
// 重写 router.history 方法
// #############################
(() => {
const routerHistoryPush = _routerHistory.push
_routerHistory.push = function (...args) {
console.debug('🚥 [router]', 'push: args :>> ', args)
return routerHistoryPush.call(this, ...args)
}
const routerHistoryReplace = _routerHistory.replace
_routerHistory.replace = function (...args) {
console.debug('🚥 [router]', 'replace: args :>> ', args)
// lastNavigationInfo.replace = true;
return routerHistoryReplace.call(this, ...args)
}
const routerHistoryGo = _routerHistory.go
_routerHistory.go = function (...args) {
console.debug('🚥 [router]', 'go: args :>> ', args)
return routerHistoryGo.call(this, ...args)
}
})/* () */;
// #############################
// 重写 window.history 方法
// #############################
(() => {
const browserHistoryBack = window.history.back
window.history.back = function (...args) {
console.debug('🌐 [Browser]', 'history.back: args :>> ', args)
return browserHistoryBack.call(this, ...args)
}
const browserHistoryForward = window.history.forward
window.history.forward = function (...args) {
console.debug('🌐 [Browser]', 'history.forward: args :>> ', args)
return browserHistoryForward.call(this, ...args)
}
const browserHistoryGo = window.history.go
window.history.go = function (...args) {
console.debug('🌐 [Browser]', 'history.go: args :>> ', args)
return browserHistoryGo.call(this, ...args)
}
const browserHistoryPushState = window.history.pushState
window.history.pushState = function (...args) {
console.debug('🌐 [Browser]', 'history.pushState: args :>> ', args)
return browserHistoryPushState.call(this, ...args)
}
const browserHistoryReplaceState = window.history.replaceState
window.history.replaceState = function (...args) {
console.debug('🌐 [Browser]', 'history.replaceState: args :>> ', args)
return browserHistoryReplaceState.call(this, ...args)
}
})/* () */;
router.beforeEach(async (to) => {
if (to.name === 'Page3') {
return { name: 'Page2' }
}
})
router.afterEach(async (to, from, failure) => {
if (failure) return
if (from === START_LOCATION) {
startPosition = history.state.position
curPosition = startPosition - 1
}
const newPostion = history.state.position
// console.log('history.state.position :>> ', history.state.position);
console.log('startPosition :>> ', startPosition);
console.log('newPostion :>> ', newPostion);
const delta = newPostion - curPosition
if (newPostion > curPosition) {
console.log('👉🏻');
} else if (newPostion < curPosition) {
console.log('👈🏻');
} else {
console.log('👌🏻');
}
console.log('delta :>> ', delta);
curPosition = newPostion;
console.log(`%c${'-'.repeat(80)}`, 'color: #409EFF;')
})
}

View File

@ -1,27 +1,16 @@
import { createRouter, createWebHistory } from 'vue-router'
import { routes, handleHotUpdate } from 'vue-router/auto-routes'
import { setupRouterGuard } from './guard'
export const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
// routes: [
// {
// path: '/',
// name: 'home',
// component: HomeView
// },
// {
// path: '/about',
// name: 'about',
// // route level code-splitting
// // this generates a separate chunk (About.[hash].js) for this route
// // which is lazy-loaded when the route is visited.
// component: () => import('../views/AboutView.vue')
// }
// ],
routes
routes,
strict: true
})
export default router
if ($__DEV__) Object.assign(window, { router })
setupRouterGuard(router)
if (import.meta.hot) {
handleHotUpdate(router)

21
src/types/router.ts Normal file
View File

@ -0,0 +1,21 @@
import 'vue-router'
// 为了确保这个文件被当作一个模块,添加至少一个 `export` 声明
export { }
// declare module 'vue-router' {
// interface RouteMeta {
// // fromList?: RouteLocationNormalized[]
// }
// interface Router {
// stack: {
// // list: RouteLocationNormalizedLoaded[]
// // currentStackIndex: number
// }
// }
// interface RouteLocationNormalizedGeneric {
// // from: RouteLocationNormalizedLoaded
// // stackIndex: number
// }
// }

12
src/types/shims.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
export {}
declare global {
const $__DEV__: boolean
}
/* declare module 'vue' {
export interface ComponentCustomProperties {
$__DEV__: boolean;
}
}
*/