Uni Mini Router

website·Indexed 30 days ago

https://moonofweisheng.github.io/uni-mini-router/

A lightweight routing library based on Vue 3 and the uni-app framework. It provides APIs and functionality similar to Vue Router to help developers implement route jumping, parameter passing, and interception in uni-app projects. Supports APP, H5, and WeChat Mini Programs.

Tokens
2.6K
Snippets
16
Records
25
Agent score
74%

What's inside Uni Mini Router

  1. Overview of uni-mini-router for uni-app

    uni-mini-router is a lightweight routing library built for vue3 and the uni-app framework. It provides an API surface similar to Vue Router to simplify common routing tasks in uni-app, such as page navigation, parameter passing, and route interception. It supports standard navigation, redirects, and TabBar page switching across multiple platforms including APP, H5, and WeChat Mini Programs.
  2. Initialize Uni Mini Router in main.ts

    Register the router instance in the uni-app entry file using app.use(router) within the createApp function.
    import { createSSRApp } from 'vue'
    import App from './App.vue'
    import router from './router'
    
    export function createApp() {
      const app = createSSRApp(App)
      app.use(router)
      return {
        app
      }
    }
  3. Pass complex objects between pages

    Since URLs have length limits and special characters can cause failures, complex objects should be stringified and encoded using encodeURIComponent before being passed via params or query. On the receiving end, use decodeURIComponent and JSON.parse.
    // Sending page
    const user = { name: '小星星', label: '小熊熊' };
    router.push({ 
      name: 'user', 
      params: { user: encodeURIComponent(JSON.stringify(user)) } 
    });
    
    // Receiving page (user.vue)
    onLoad((option) => {
      if (option && option.user) {
        const user = JSON.parse(decodeURIComponent(option.user))
      }
    })
    
  4. Implement global navigation guards with beforeEach and afterEach

    The router supports two global navigation guards: beforeEach (executed before navigation) and afterEach (executed after navigation).

    Important Caveats & Fixes:

    • Async/Await: Ensure proper handling of async/await in beforeEach to avoid navigation failures (fixed in v0.1.2).
    • Non-Async Guards: Navigation guards that are not defined as async functions are now supported (fixed in v0.1.3).
    • H5 Platform: Fixed an issue where beforeEach did not execute after packaging for the H5 platform (fixed in v0.1.4).
    • Configuration: Navigation is now possible even if no navigation guards are configured (fixed in v0.0.8).
  5. Choose and install a route table generation plugin

    Uni Mini Router requires a route table generated from pages.json. You must choose one of the following two plugins:

    1. uni-parse-pages: Does not depend on Vite. It reads pages.json during every hot reload. This is the only option that supports route information hot updates when compiling to mini-programs. (Supported from uni-mini-router@0.1.0 onwards).
    2. uni-read-pages-vite: Depends on Vite. It reads pages.json at build time and injects the route table as a global variable. Changes to pages.json require a rebuild to take effect.
    # To install uni-parse-pages
    npm i add uni-parse-pages --save
    
    # To install uni-read-pages-vite
    npm i add uni-read-pages-vite --save
  6. Configure Uni Mini Router routes

    Create a router folder in the src directory (or root directory for HBuilderX projects) and create an index.ts file. You can generate the route table using one of two methods: uni-parse-pages or uni-read-pages-vite.
    // Option 1: Using uni-parse-pages
    import { createRouter } from 'uni-mini-router'
    import pagesJson from '../pages.json'
    import pagesJsonToRoutes from 'uni-parse-pages'
    
    const routes = pagesJsonToRoutes(pagesJson)
    const router = createRouter({
      routes: [...routes]
    })
    export default router
    
    // OR Option 2: Using uni-read-pages-vite
    import { createRouter } from 'uni-mini-router'
    const router = createRouter({
      routes: [...ROUTES] // ROUTES is typically provided via vite define
    })
    export default router
  7. Define named routes in pages.json

    To use named routing for navigation, add a globally unique name field to the page objects in pages.json.
    {
      "pages": [
        {
          "path": "pages/home/Home",
          "name": "home",
          "style": {
            "navigationBarTitleText": "首页"
          }
        },
        {
          "path": "pages/login/Login",
          "name": "login",
          "style": {
            "navigationBarTitleText": ""
          }
        }
      ]
    }
  8. Configure uni-read-pages-vite in vite.config.ts

    When using uni-read-pages-vite, you must inject the generated route table into the global ROUTES variable via the Vite define configuration. The configuration differs slightly based on how the project was created.
    // For CLI-created projects
    import { defineConfig } from "vite";
    import uni from "@dcloudio/vite-plugin-uni";
    import TransformPages from 'uni-read-pages-vite'
    
    export default defineConfig({
      plugins: [uni()],
      define: {
        ROUTES: new TransformPages().routes,
      }
    });
    
    // For HbuilderX-created projects
    import { defineConfig } from "vite";
    import uni from "@dcloudio/vite-plugin-uni";
    import TransformPages from 'uni-read-pages-vite'
    
    export default defineConfig({
      plugins: [uni()],
      define: {
        ROUTES: new TransformPages(__dirname).routes,
      }
    });
  9. Handle navigation guard limitations in Uni Mini Router

    Be aware of the following limitations when using navigation guards:

    1. First-screen trigger: Pre-navigation guards are not triggered on the initial page load. To handle business logic for the first screen, create a blank landing page to perform checks before redirecting to the target route.
    2. Tabbar navigation: Transitions between Tabbar pages do not use the routing API and therefore cannot be intercepted by guards.
    3. Non-API redirects: Any navigation that does not utilize the routing API cannot be intercepted.