UNPKG

@meng-xi/uni-router

Version:

为 uni-app 提供类似 vue-router 风格的路由

2 lines (1 loc) 5.38 kB
(function(p,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],f):(p=typeof globalThis<"u"?globalThis:p||self,f(p.MxRouter={},p.Vue))})(this,function(p,f){"use strict";var l=(e=>(e.NAVIGATION_ABORTED="NAVIGATION_ABORTED",e.NAVIGATION_REDIRECT="NAVIGATION_REDIRECT",e.NAVIGATION_FAILED="NAVIGATION_FAILED",e.INVALID_METHOD="INVALID_METHOD",e))(l||{});const b=["app","app-plus","app-plus-nvue","app-nvue","app-android","app-ios","app-harmony"];class c extends Error{type;location;constructor(t,n,r){super(n),this.type=t,this.location=r,Object.setPrototypeOf(this,c.prototype)}static navigationAborted(){return new c(l.NAVIGATION_ABORTED,"Navigation aborted by guard")}static navigationRedirect(t){return new c(l.NAVIGATION_REDIRECT,"Navigation redirected",t)}static navigationFailed(t){return new c(l.NAVIGATION_FAILED,t||"Navigation failed")}static invalidMethod(t){return new c(l.INVALID_METHOD,`Navigation method ${t} not available`)}}function g(e,t){if(e.startsWith("tabBar/"))return e.startsWith("/")?e:`/${e}`;const n=e.startsWith("/")?e:`/${e}`;if(e.includes("?")||!t)return n;const r=Object.keys(t).filter(s=>t[s]!==void 0&&t[s]!==null).map(s=>`${encodeURIComponent(s)}=${encodeURIComponent(String(t[s]))}`).join("&");return r?`${n}?${r}`:n}function d(e){if(!e)return null;let t={};const n=String(process.env.UNI_PLATFORM).toString().toLowerCase();return["mp-weixin","mp-alipay","mp-baidu","mp-toutiao","mp-qq"].includes(n)&&(t=e.options||{}),["h5"].includes(n)&&(t=e.$vm?.$route?.query||{}),["app-plus"].includes(n)&&(t=e.$vm?.$mp?.query||{}),{path:e.route||"",fullPath:g(e.route||""),query:t}}function I(e){if(typeof e=="string")return{path:e};const t=typeof e.query=="object"&&e.query!==null?Object.fromEntries(Object.entries(e.query).map(([n,r])=>[n,String(r)])):void 0;return{path:e.path,query:t}}function A(){return!0}function T(e){throw new Error(`[uni-router error]:${e}`)}function y(e){const t={};return Object.keys(e).map(n=>{t[n]=f.unref(e[n])}),t}function m(){const e=String(process.env.UNI_PLATFORM).toString().toLowerCase();return b.includes(e)}class a{static instance;routes;beforeEachHooks;afterEachHooks;customGetCurrentRoute;constructor(t={}){this.routes=t.routes||[],this.beforeEachHooks=[],this.afterEachHooks=[],this.customGetCurrentRoute=t.customGetCurrentRoute}static getInstance(t){return a.instance||(a.instance=new a(t)),a.instance}static push(t,n){return a.getInstance().push(t,n)}push(t,n){return this.navigate(t,"navigateTo",n)}static replace(t){return a.getInstance().replace(t)}replace(t){return this.navigate(t,"redirectTo")}static launch(t){return a.getInstance().launch(t)}launch(t){return this.navigate(t,"reLaunch")}static tab(t){return a.getInstance().tab(t)}tab(t){return this.navigate(t,"switchTab")}static go(t=-1,n){a.getInstance().go(t,n)}go(t=-1,n){const r={delta:Math.abs(t),...m()&&n&&{animationType:n.type||"pop-out",animationDuration:n.duration||300}};uni.navigateBack(r)}static back(t){a.getInstance().back(t)}back(t){this.go(-1,t)}static beforeEach(t){a.getInstance().beforeEach(t)}beforeEach(t){this.beforeEachHooks.push(t)}static afterEach(t){a.getInstance().afterEach(t)}afterEach(t){this.afterEachHooks.push(t)}static setCustomGetCurrentRoute(t){a.getInstance().setCustomGetCurrentRoute(t)}setCustomGetCurrentRoute(t){this.customGetCurrentRoute=t}static getCurrentRoute(){return a.getInstance().getCurrentRoute()}getCurrentRoute(){if(this.customGetCurrentRoute)return this.customGetCurrentRoute();const t=getCurrentPages();return t.length>0?d(t[t.length-1]):null}async navigate(t,n,r){const{path:s,query:h}=I(t),u=this.getCurrentRoute(),o={path:s,query:h||{},fullPath:g(s,h)};try{for(const i of this.beforeEachHooks)await this.runGuard(i,o,u);n==="switchTab"?await this.callMxMethod("switchTab",g(s)):await this.callMxMethod(n,o.fullPath,r);for(const i of this.afterEachHooks)i(o,u)}catch(i){if(i instanceof c&&i.type===l.NAVIGATION_REDIRECT&&i.location)return this.push(i.location);throw c.navigationFailed(i instanceof Error?i.message:String(i))}}runGuard(t,n,r){return new Promise((s,h)=>{const u=o=>{o===!1?h(c.navigationAborted()):typeof o=="string"||typeof o=="object"&&o!==null?h(c.navigationRedirect(o)):s()};try{const o=t(n,r,u);o!==void 0&&Promise.resolve(o).then(i=>{i===!1?h(c.navigationAborted()):typeof i=="string"||typeof i=="object"&&i!==null?h(c.navigationRedirect(i)):s()}).catch(h)}catch(o){h(o)}})}callMxMethod(t,n,r){return new Promise((s,h)=>{const u=uni[t],o={url:n};m()&&r&&(o.animationType=r.type||"pop-in",o.animationDuration=r.duration||300),typeof u=="function"?u(o).then(s).catch(i=>h(c.navigationFailed(i instanceof Error?i.message:String(i)))):h(c.invalidMethod(t))})}}function N(e){const t=f.ref(null),n=f.ref(!1);async function r(){const u=f.unref(t);return u||T("The router instance has not been obtained, please make sure that the router has been rendered when performing the router operation!"),await f.nextTick(),u}function s(u){f.onUnmounted(()=>{t.value=null,n.value=null}),!(f.unref(n)&&A()&&u===f.unref(t))&&(t.value=u,n.value=!0,f.watch(()=>e,()=>{e&&u.setProps(y(e))},{immediate:!0,deep:!0}))}return[s,{setProps:async u=>{(await r()).setProps(u)}}]}p.Router=a,p.buildUrl=g,p.getCurrentRoute=d,p.parseLocation=I,p.useMxRouter=N,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});