feat: 添加登录页面URL配置及页面权限控制

- 在.env文件中新增VITE_LOGIN_URL配置
- 在App.vue中引入并调用usePageAuth以实现页面权限控制
- 更新route.ts以使用环境变量中的登录页面URL
This commit is contained in:
陈剑术 2025-06-04 12:25:13 +08:00
parent f23d8128f9
commit dcae738e69
4 changed files with 55 additions and 1 deletions

3
env/.env vendored
View File

@ -7,6 +7,9 @@ VITE_WX_APPID = 'wxa2abb91f64032a2b'
# h5部署网站的base配置到 manifest.config.ts 里的 h5.router.base # h5部署网站的base配置到 manifest.config.ts 里的 h5.router.base
VITE_APP_PUBLIC_BASE=/ VITE_APP_PUBLIC_BASE=/
# 登录页面
VITE_LOGIN_URL = '/pages/login/index'
VITE_SERVER_BASEURL = 'https://ukw0y1.laf.run' VITE_SERVER_BASEURL = 'https://ukw0y1.laf.run'
VITE_UPLOAD_BASEURL = 'https://ukw0y1.laf.run/upload' VITE_UPLOAD_BASEURL = 'https://ukw0y1.laf.run/upload'

View File

@ -1,6 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app' import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only' import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import { usePageAuth } from '@/hooks/usePageAuth'
usePageAuth()
onLaunch(() => { onLaunch(() => {
console.log('App Launch') console.log('App Launch')

48
src/hooks/usePageAuth.ts Normal file
View File

@ -0,0 +1,48 @@
import { onLoad } from '@dcloudio/uni-app'
import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
import { useUserStore } from '@/store'
const loginRoute = import.meta.env.VITE_LOGIN_URL
const isDev = import.meta.env.DEV
// 检查当前页面是否需要登录
export function usePageAuth() {
onLoad((options) => {
// 获取当前页面路径
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const currentPath = `/${currentPage.route}`
// 获取需要登录的页面列表
let needLoginPages: string[] = []
if (isDev) {
needLoginPages = getNeedLoginPages()
} else {
needLoginPages = _needLoginPages
}
// 检查当前页面是否需要登录
const isNeedLogin = needLoginPages.includes(currentPath)
if (!isNeedLogin) {
return
}
// 检查是否已登录
const userStore = useUserStore()
const hasLogin = userStore.isLogined
if (hasLogin) {
return
}
// 构建重定向URL
const queryString = Object.entries(options || {})
.map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
.join('&')
const currentFullPath = queryString ? `${currentPath}?${queryString}` : currentPath
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currentFullPath)}`
// 重定向到登录页
uni.redirectTo({ url: redirectRoute })
})
}

View File

@ -8,7 +8,7 @@ import { useUserStore } from '@/store'
import { needLoginPages as _needLoginPages, getNeedLoginPages, getLastPage } from '@/utils' import { needLoginPages as _needLoginPages, getNeedLoginPages, getLastPage } from '@/utils'
// TODO Check // TODO Check
const loginRoute = '/pages/login/index' const loginRoute = import.meta.env.VITE_LOGIN_URL
const isLogined = () => { const isLogined = () => {
const userStore = useUserStore() const userStore = useUserStore()