| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281 |
- import { pages, subPackages, tabBar } from '@/pages.json'
- import { isMpWeixin } from './platform'
- const getLastPage = () => {
- // getCurrentPages() 至少有1个元素,所以不再额外判断
- // const lastPage = getCurrentPages().at(-1)
- // 上面那个在低版本安卓中打包回报错,所以改用下面这个【虽然我加了src/interceptions/prototype.ts,但依然报错】
- const pages = getCurrentPages()
- return pages[pages.length - 1]
- }
- /** 判断当前页面是否是tabbar页 */
- export const getIsTabbar = () => {
- if (!tabBar) {
- return false
- }
- if (!tabBar.list.length) {
- // 通常有tabBar的话,list不能有空,且至少有2个元素,这里其实不用处理
- return false
- }
- const lastPage = getLastPage()
- const currPath = lastPage.route
- return !!tabBar.list.find((e) => e.pagePath === currPath)
- }
- /**
- * 获取当前页面路由的 path 路径和 redirectPath 路径
- * path 如 ‘/pages/login/index’
- * redirectPath 如 ‘/pages/demo/base/route-interceptor’
- */
- export const currRoute = () => {
- const lastPage = getLastPage()
- const currRoute = (lastPage as any).$page
- // console.log('lastPage.$page:', currRoute)
- // console.log('lastPage.$page.fullpath:', currRoute.fullPath)
- // console.log('lastPage.$page.options:', currRoute.options)
- // console.log('lastPage.options:', (lastPage as any).options)
- // 经过多端测试,只有 fullPath 靠谱,其他都不靠谱
- const { fullPath } = currRoute as { fullPath: string }
- // console.log(fullPath)
- // eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
- // eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
- return getUrlObj(fullPath)
- }
- const ensureDecodeURIComponent = (url: string) => {
- if (url.startsWith('%')) {
- return ensureDecodeURIComponent(decodeURIComponent(url))
- }
- return url
- }
- /**
- * 解析 url 得到 path 和 query
- * 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
- * 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
- */
- export const getUrlObj = (url: string) => {
- const [path, queryStr] = url.split('?')
- // console.log(path, queryStr)
- if (!queryStr) {
- return {
- path,
- query: {},
- }
- }
- const query: Record<string, string> = {}
- queryStr.split('&').forEach((item) => {
- const [key, value] = item.split('=')
- // console.log(key, value)
- query[key] = ensureDecodeURIComponent(value) // 这里需要统一 decodeURIComponent 一下,可以兼容h5和微信y
- })
- return { path, query }
- }
- /**
- * 得到所有的需要登录的pages,包括主包和分包的
- * 这里设计得通用一点,可以传递key作为判断依据,默认是 needLogin, 与 route-block 配对使用
- * 如果没有传 key,则表示所有的pages,如果传递了 key, 则表示通过 key 过滤
- */
- export const getAllPages = (key = 'needLogin') => {
- // 这里处理主包
- const mainPages = [
- ...pages
- .filter((page) => !key || page[key])
- .map((page) => ({
- ...page,
- path: `/${page.path}`,
- })),
- ]
- // 这里处理分包
- const subPages: any[] = []
- subPackages.forEach((subPageObj) => {
- // console.log(subPageObj)
- const { root } = subPageObj
- subPageObj.pages
- .filter((page) => !key || page[key])
- .forEach((page: { path: string } & Record<string, any>) => {
- subPages.push({
- ...page,
- path: `/${root}/${page.path}`,
- })
- })
- })
- const result = [...mainPages, ...subPages]
- // console.log(`getAllPages by ${key} result: `, result)
- return result
- }
- /**
- * 得到所有的需要登录的pages,包括主包和分包的
- * 只得到 path 数组
- */
- export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)
- /**
- * 得到所有的需要登录的pages,包括主包和分包的
- * 只得到 path 数组
- */
- export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)
- /**
- * 根据微信小程序当前环境,判断应该获取的BaseUrl
- */
- export const getEnvBaseUrl = () => {
- // 请求基准地址
- let baseUrl = import.meta.env.VITE_SERVER_BASEURL
- // 微信小程序端环境区分
- if (isMpWeixin) {
- const {
- miniProgram: { envVersion },
- } = uni.getAccountInfoSync()
- switch (envVersion) {
- case 'develop':
- baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_DEVELOP || baseUrl
- break
- case 'trial':
- baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_TRIAL || baseUrl
- break
- case 'release':
- baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_RELEASE || baseUrl
- break
- }
- }
- return baseUrl
- }
- /**
- * 根据微信小程序当前环境,判断应该获取的UPLOAD_BASEURL
- */
- export const getEnvBaseUploadUrl = () => {
- // 请求基准地址
- let baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL
- // 微信小程序端环境区分
- if (isMpWeixin) {
- const {
- miniProgram: { envVersion },
- } = uni.getAccountInfoSync()
- switch (envVersion) {
- case 'develop':
- baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_DEVELOP || baseUploadUrl
- break
- case 'trial':
- baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_TRIAL || baseUploadUrl
- break
- case 'release':
- baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_RELEASE || baseUploadUrl
- break
- }
- }
- return baseUploadUrl
- }
- // 获取登录的code
- export const getLoginCode = () => {
- return new Promise((resolve, reject) => {
- uni.login({
- success: (res) => {
- if (res.code) resolve(res.code)
- else reject(res)
- },
- fail: (err) => {
- reject(err)
- },
- })
- })
- }
- // 回显字典
- export const getLabel = (code: string, options: any) => {
- let label = ''
- if (code) {
- label = options.find((e: any) => e.value == code)?.label || ''
- }
- return label || code
- }
- // 回显字典颜色
- export const getLabelColor = (code: string, options: any) => {
- let color = ''
- if (code) {
- color = options.find((e: any) => e.value == code)?.color || ''
- }
- return color
- }
- // 字典转为label和value
- export const dictLabel = (lists: any[]) => {
- let datas: any = []
- if (!lists.length) return datas
- datas = lists.map((item) => {
- return {
- value: item.code,
- label: item.name,
- }
- })
- return datas
- }
- // 数组根据id去重
- export function uniqueItems(items: any) {
- const uniqueData = items.filter(
- (item: any, index: any, self: any) => index === self.findIndex((t: any) => t.id === item.id),
- )
- return uniqueData
- }
- // 跳转至登录页(自动登录)
- export function toLogin(duration = 0) {
- setTimeout(() => {
- uni.reLaunch({
- url: `/pages/login/index`,
- })
- }, duration)
- }
- // 跳转至登录页(不自动登录)
- export function toLoginWait(duration = 0) {
- setTimeout(() => {
- uni.reLaunch({
- url: `/pages/login/index?isLogout=1`,
- })
- }, duration)
- }
- // 重定向到上传系统文件
- export function redirectToUpload() {
- const url = "https://service.1ai.ltd/webview-upload/index.html"
- uni.redirectTo({
- url: `/pages/webview/index?url=${encodeURIComponent(url)}`,
- })
- }
- // 重定向到首页
- export function reLaunchToHome() {
- uni.reLaunch({
- url: `/pages/index/index`,
- })
- }
- // 时间转义
- export function timestampToDatetime(timestamp) {
- let str = String(timestamp)
- let ts = Number(str.length == 10 ? `${str}000` : str)
- let date = new Date(ts);
- let year = date.getFullYear();
- let month = ("0" + (date.getMonth() + 1)).slice(-2);
- let day = ("0" + date.getDate()).slice(-2);
- let hours = ("0" + date.getHours()).slice(-2);
- let minutes = ("0" + date.getMinutes()).slice(-2);
- let seconds = ("0" + date.getSeconds()).slice(-2);
-
- return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
- }
|