feat(router): 添加404页面并处理不存在的路由
在路由配置中添加404页面常量,并创建对应的404页面组件。修改路由拦截器,当访问不存在的路由时自动跳转到404页面。同时优化路由拦截器的返回逻辑,明确区分阻止和允许路由继续执行的情况。
This commit is contained in:
30
src/pages/404/index.vue
Normal file
30
src/pages/404/index.vue
Normal file
@@ -0,0 +1,30 @@
|
||||
<script lang="ts" setup>
|
||||
import { HOME_PAGE } from '@/utils'
|
||||
|
||||
definePage({
|
||||
style: {
|
||||
// 'custom' 表示开启自定义导航栏,默认 'default'
|
||||
navigationStyle: 'custom',
|
||||
},
|
||||
})
|
||||
|
||||
function goBack() {
|
||||
// 当pages.config.ts中配置了tabbar页面时,使用switchTab切换到首页
|
||||
// 否则使用navigateTo返回首页
|
||||
uni.switchTab({ url: HOME_PAGE })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<view class="h-screen flex flex-col items-center justify-center">
|
||||
<view> 404 </view>
|
||||
<view> 页面不存在 </view>
|
||||
<button class="mt-6 w-40 text-center" @click="goBack">
|
||||
返回首页
|
||||
</button>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
//
|
||||
</style>
|
||||
@@ -10,6 +10,7 @@ export const isNeedLoginMode = LOGIN_STRATEGY === LOGIN_STRATEGY_MAP.DEFAULT_NEE
|
||||
|
||||
export const LOGIN_PAGE = '/pages/login/login'
|
||||
export const REGISTER_PAGE = '/pages/login/register'
|
||||
export const NOT_FOUND_PAGE = '/pages/404/index'
|
||||
|
||||
export const LOGIN_PAGE_LIST = [LOGIN_PAGE, REGISTER_PAGE]
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { isMp } from '@uni-helper/uni-env'
|
||||
import { useTokenStore } from '@/store/token'
|
||||
import { isPageTabbar, tabbarStore } from '@/tabbar/store'
|
||||
import { getAllPages, getLastPage, HOME_PAGE, parseUrlToObj } from '@/utils/index'
|
||||
import { EXCLUDE_LOGIN_PATH_LIST, isNeedLoginMode, LOGIN_PAGE, LOGIN_PAGE_ENABLE_IN_MP } from './config'
|
||||
import { EXCLUDE_LOGIN_PATH_LIST, isNeedLoginMode, LOGIN_PAGE, LOGIN_PAGE_ENABLE_IN_MP, NOT_FOUND_PAGE } from './config'
|
||||
|
||||
export const FG_LOG_ENABLE = false
|
||||
export function judgeIsExcludePath(path: string) {
|
||||
@@ -43,6 +43,13 @@ export const navigateToInterceptor = {
|
||||
path = `${baseDir}/${path}`
|
||||
}
|
||||
|
||||
// 处理路由不存在的情况
|
||||
if (getAllPages().every(page => page.path !== path)) {
|
||||
console.warn('路由不存在:', path)
|
||||
uni.navigateTo({ url: NOT_FOUND_PAGE })
|
||||
return false // 明确表示阻止原路由继续执行
|
||||
}
|
||||
|
||||
// 处理直接进入路由非首页时,tabbarIndex 不正确的问题
|
||||
tabbarStore.setAutoCurIdx(path)
|
||||
|
||||
@@ -104,9 +111,9 @@ export const navigateToInterceptor = {
|
||||
uni.navigateTo({ url: redirectUrl })
|
||||
return false // 修改为false,阻止原路由继续执行
|
||||
}
|
||||
return true // 明确表示允许路由继续执行
|
||||
}
|
||||
// #endregion 2/2 默认不需要登录的情况(黑名单策略) ---------------------------
|
||||
return true // 明确表示允许路由继续执行
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user