uni-simple-router
- A router specially designed for uniapp, deeply integrated with uniapp
- Wild mini-programs, apps and H5 terminals
- H5 can be fully developed using vue-router
- Modularity, query, wildcard, routing parameters
- Make uni-app implement nested routing (only the H5 side uses vue-router completely)
- Uniapp uses many Vue APIs, but the routing management function is still relatively lacking compared to vue-router, such as global navigation guards.
Official Documentation:/v2/start/
1. Get started quickly
// Projects created for uniapp HBuilder, non-cli-built// 1⃣ NPM installationnpm install uni-simple-router // 2⃣ Initializationnpm install uni-read-pages // In conjunction with automatic reading as the routing table, the source code is as follows: Expand the second // Configurationconst TransformPages = require('uni-read-pages') const tfPages = new TransformPages() = { configureWebpack: { plugins: [ new ({ // 1⃣ Configure global variables // ROUTES: () // 2⃣ include can customize and resolve the configuration of routing fields. Default ['path', 'name', 'aliasPath'] ROUTES: (()=>{ const tf = new TransformPages({ includes: ['path', 'name', 'aliasPath'] }) return () },true) }) ] } } // /Applications//Contents/HBuilderX/plugins/uniapp-cli/node_modules/webpack minewebpackPackage path,In softwarecontentsThe software comes with the package filewebpack
Expand one: DefinePlugin for webpack plugin
- Allows to create a global variable that can be configured at compile time
- Scenario: Differentiate different development modes of processing
// 1⃣ Usage: Each key value passed into DefinePlugin is one flag or multiple identifiers connectednew ({ PRODUCTION: (true), BROWSER_SUPPRTS_HTML5: true, VERSION: ('abcde'), TWO: '1+1', 'typeof window': ('object') }) //How to use('Running App version', VERSION) if(!BROWSER_SUPPRTS_HTML5) require("html5shiv") // 2⃣ Function tags to enable and disable functions in the build as a flagnew ({ 'SHOW_PRESSION': (true) }) // 3⃣ Service: You can configure URLs in different environmentsnew ({ 'DEV_URL': (url_dev), 'PRO_URL': (url_pro) })
Expand two: uni-read-pages how to get the route in
// Dependency source code - Get any information in the file through the node's path module (partially personal comments)const path = require('path') const CONFIG = { includes: ['path', 'aliasPath', 'name'] } // Get the route parameter attributes by default// () Return the current working directory of the process// (url1, 'abc') => url1/abc const rootPath = ((), 'node_modules'); // Get the root path /** parse absolute path * @param {Object} dir */ function resolvePath(dir) { return (rootPath, dir); } // kindclass TransformPages { constructor(config) { // Combination Customize to get configuration properties config = { ...CONFIG, ...config }; = config; // ↓Native file path (the webpack module path included in the HBuilderX package file) /Applications//Contents/HBuilderX/plugins/uniapp-cli/node_modules/webpack = require(resolvePath('webpack')); = require(resolvePath('@dcloudio/uni-cli-shared/lib/')); // TODO: According to the routing information in CONFIG analysis and the routing under the subcontractor of the applet = ().concat(()); } // Get all the contents under Return to json get pagesJson() { return (); } // Generate directly available routes by reading files getPagesRoutes(pages = , rootPath = null) { const routes = []; for (let i = 0; i < ; i++) { const item = pages[i]; const route = {}; for (let j = 0; j < ; j++) { const key = [j]; let value = item[key]; if (key === 'path') { value = rootPath ? `/${rootPath}/${value}` : `/${value}` } if (key === 'aliasPath' && i == 0 && rootPath == null) { route[key] = route[key] || '/' } else if (value !== undefined) { route[key] = value; } } (route); } return routes; } // parse the mini program subcontract path getNotMpRoutes() { const { subPackages } = ; let routes = []; if (subPackages == null || == 0) { return []; } for (let i = 0; i < ; i++) { const subPages = subPackages[i].pages; const root = subPackages[i].root; const subRoutes = (subPages, root); routes = (subRoutes) } return routes } /** * Single page object analysis * @param {Object} pageCallback * @param {Object} subPageCallback */ parsePages(pageCallback, subPageCallback) { (, pageCallback, subPageCallback) } } = TransformPages
2. H5 mode
2.1 Routing configuration
import {RouterMount,createRouter} from 'uni-simple-router'; const router = createRouter({ //Routing configuration routes: [ { path: '/pages/index/index', // Must be the same as extra: { pageStyle: { color: '#f00' }// and other custom parameters } } ] }) // Components can be passed this.$Route View routing meta information
2.2 Fully use vue-router to develop (H5 end)
- When nested routing, if you use the name method to jump, only this.$({ name: children1 }) is supported.
// Using vue-router to develop will lose the life cycle of uniappconst router = createRouter({ h5: { vueRouterDev: true, // Develop completely using vue-router, default is false }, //Routing configuration routes: [ { path: '/', name: 'home', component: () => import('@/common/router/'), // Nested routing (H5 end only), the mini-program will reopen the page children: [ { path: 'home/children1', name: 'children1', component: () => import('@/common/router/') }, { path: 'home/children2', name: 'children2', component: () => import('@/common/router/') } ] } ] })
2.3 H5 routing parameters
// In addition to vue-router, beautified url can define aliasPath variable and set routing aliases (browser address bar display name)// Setting of alias. If an alias is set, the path of aliasPath must be used to take effect by pushing the path.const router = createRouter({ routes:[{ name:'router1', //In order to be compatible with other ends, the path must be missing at this time and must match the page path in path: "/pages/tabbar/tabbar-1/tabbar-1", aliasPath: '/tabbar-1', },] }); // uni-simple-router routing jump// AliasPath named route => name pass parameter requires paramsthis.$({ name: 'detail', params: { id: 1 } }) // With query parameters, it becomes /home/id=1 => path corresponding to query, params invalidthis.$({ path: '/pages/index/detail', query: { id: 1 }})
2.4 H5 side route captures all routes or 404 routes
path:'*' // Usually used for client 404 errors. If it is history mode, the server needs to be configured correctly.path: '/detail-*' // The priority of the route is based on Definition order
2.5 Lazy loading of routes
When building applications, the Javascript package will become very large, affecting page loading, dividing the corresponding components of different routes into different code blocks, and then loading the corresponding components when the route is accessed.
const Foo = () => import('./') // Use components to chunk const Foo = () => import(/*webpackChunkName:"group-foo"*/ './') const Bar = () => import(/*webpackChunkName:"group-foo"*/ './')
3. Mini Program Mode
Note: The mini program series cannot intercept native tabbar and native navigation return. If you need to intercept custom tabbar and header
When switching through API, methods like() and this.$() will trigger interception; only the native tabbar at the bottom will not trigger interception when switching through API;
-
Force trigger guard: forceGuardEach(replaceAll, false) Each time the API is called, all guards that have been declared will be triggered again according to the process.
- Default to the mini-program: plug-in api jump, uni navigation api jump and first-screen loading
- Use route guard: Force trigger by clicking events, mixing into the onshow callback trigger
Jump route lock: animationDuration is reserved for redirection\push enough time, and the next jump will be released after the switching is completed.
const router = createRouter({ platform: .VUE_APP_PLATFORM, // ① Routing lock applet: { animationDuration: 300 // Default 300ms // animationDuration: 0 // Inaccurate Only capture complete functions under jump API }, // ②Elegant unlocking: 0 means next(false), 1 means next(unknownType), 2 means locking status, prohibit jumping, 3 means that when obtaining the page stack, the page stack is not level enough to obtain routerErrorEach:(error, router) => { if ( === 3) { router.$lockStatus = false } }, routes: [...ROUTES] })
4. Routing jump
4.1 Component jump
In vue-router, you can use the router-link component to perform page redirection. Uni-simple-router also provides similar components, which require manual registration
// import Link from './node_modules/uni-simple-router/dist/' ('Link', Link)
// Jump directly through path and specify the jump type <Link to="/tabbar1" navType="pushTab"> <button type="primary">usepathObject jump</button> </Link>
4.2 Programming Navigation
- Get the routing object through this.$Router; push, pushTab, replace, back and other APIs for routing jump
- Note: path is matched with query parameters, name is matched with params parameters
- Navigation usage is the same as vue-router
5. Cross-platform mode
5.1 Enjoy the life cycle in advance
Since uniapp only uses onLoad to accept options parameters, onShow does not accept; when passing deep object parameters, it needs to be encoded first and then passed to decode.
// Dynamically change parameters to make onLoad and onShow support options const router = createRouter({ platform: .VUE_APP_PLATFORM, routes: [...ROUTES], beforeProxyHooks: { onLoad(options, next){ next([]); }, onShow([options], next){ (this); const args=options||; next([args]); }, }, });
5.2 Navigation Guard
Global front guard
/** * to: Route The target to be entered * from: Route The route that the current navigation is about to leave * next: Function The resolve hook function of this method must be called, and the execution effect depends on the calling parameters of the next method. * -- next() call parameter: next hook in the pipeline; next(false) interrupts the current navigation; * -- next('/')/({path: '/'}) Jump to a different address. The current navigation is interrupted and a new navigation is performed * -- next({delta: 2, NAVTYPE: 'back'}) interrupts the current navigation, calls the new jump type, and returns to two-layer pages at the same time **/ ((to, from, next) => { // ... // 1⃣ next() // 2⃣ NAVTYPE defines the jump method, both are the same and are not required if ( == 'tabbar-5') { next({ name: 'router4', params: { msg: 'I intercepted tab5 and redirected to the route 4 page', }, NAVTYPE: 'push' }); } else{ next(); } })
Global rear guard
// Don't accept next function and don't change the navigation itself((to,from) => {})
Route exclusive guard
// Directly define beforeEnter guard on routing configurationconst router = createRouter({ routes: [{ path: '/pages/home/index', beforeEnter:(to,from,next) => { // Parameters are the same as above. Global front guard next() } }] })
Guards within components
// Configure beforeRouteLeave guard in component - directly call the beforeRouteLeave methodexport default { beforeRouteLeave(to, from, next) { // Called when navigation leaves the corresponding route of this component // This component instance can be accessed next() } }
6. Router Guard-Modular
// 1⃣ Create router folder, modular configuration file structure|+------------------------+| | router | | |+--------------------+| | | | modules | | | | |+----------------+| | | | | | | | | | | | | | | | | |+----------------+| | | | |+--------------------+| | | | |+------------------------+|
// const home = [ { path: '/pages/home/index', name: 'home' } ] export default home
// Under modules is a module reading// ① (directory, useSubdirectories, regExp) Specific details: The following three extensionsconst files = ('.',false,/.js$/) const modules = [] ().forEach(key => { if (key === './') return const item = files(key).default (...item) }) export default modules // Integrate routing modules of all modules together, routes Array
// Router Guard under routerimport modules from './modules/' import Vue from 'vue' import CreateRouter from 'uni-simple-router' import store from '@/store/' (CreateRouter) //initializationconst router = new CreateRouter({ APP: { holdTabbar: false //Default true }, h5: { vueRouterDev: true, //Develop completely using vue-router default false }, // You can also read the routing table of the file through uni-read-pages, in conjunction with // router: [...ROUTES] // ROUTES is compiled into a global variable through webpack's defaultPlugin. For details, please use it above routes: [...modules] //Route table}); //Global route front guard((to, from, next) => { // First determine whether there is routing information //If it does not exist, call the interface first to get the data}) // Global routing rear guard((to, from) => {}) export default router;
Expanding three, usage
// (directory, useSubdirectories, regExp) // directory: represents the searched directory// useSubdirectories: Indicates whether to retrieve subfolders// regExp: Regular expression matching file// Return value: resolve is a function that returns the module ID of the resolved request; keys is a function that returns an array of all possible requests that the context module can handle;//Usage scenarios: ① Used to introduce multiple components into components; ② Used to introduce a large number of public components into components;
// ①Introduce multiple components into components - webpackconst path = require('path') const files = ('@/components/home', false, /\.vue$/) //Value type ['./', '',...]const modules = {} ().forEach(key => { const name = (key, '.vue') // Remove the .vue suffix of the file name modules[name] = files(key).default || files(key) }) // modules { home: '{module style path}', detail: '{}', ... }export default { ..., data() { return {}}, components: modules }
// ②Introduce a large number of public componentsimport Vue from 'vue' // Introduce custom componentsconst requireComponents = ('../views/components',true,'/\.vue/') // traverse the path of each array().forEach(fileName => { const reqCom = requireComponents(fileName) // Get the component name const reqComName = || (/\.\/(.*)\.vue/, '$1') // Component mount (reqComName, || reqCom) })
This is all about this article about uni-simple-router. For more related uni-simple-router content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!