Uni simple Router: use Vue router to manage uniapp routes

The contents in the notes are only applicable to the uniapp project built by HBulider. For the uniapp project built by other methods, please refer to the official website of uni simple router uni simple router (hhyang. CN)

uniapp uses many APIs of vue, but it lacks the function of routing management compared with vue router, such as global navigation guard.

We can use the uniapp plug-in uni simple router to realize functions similar to Vue router, but some usage needs to be noted when multiple terminals are compatible, as we will talk about.

1, Installation

If your project does not use package, please initialize it first:

$ npm init -y

Installation dependency:

$ npm install uni-simple-router uni-read-pages

The function of uni read pages is to read the pages of uniapp JSON, as the router configuration, put pages The route configuration in Vue router is converted to the configuration in Vue router.

2, Configuration and initialization

1. Create a new Vue in the root directory config. JS file, write the following contents:

//vue.config.js
const TransformPages = require('uni-read-pages')
const {webpack} = new TransformPages()
module.exports = {
    configureWebpack: {
        plugins: [
            new webpack.DefinePlugin({
                ROUTES: webpack.DefinePlugin.runtimeValue(() => {
                    const tfPages = new TransformPages({
                        includes: ['path', 'name', 'aliasPath']
                    });
                    return JSON.stringify(tfPages.routes)
                }, true )
            })
        ]
    }
}

⚠️ Focus on line 10:

// ...
    includes: ['path', 'name', 'aliasPath']
// ...

What is included in the includes is that the router will read the field name in the pages route. If there is routing information such as meta in the future, you can add 'meta' in the includes and write the corresponding data in the pages route, which can be obtained in the router (a case will be added later)

2. Create a new root directory and write it to router JS, write the following:

// router.js
import {RouterMount,createRouter} from 'uni-simple-router';

const router = createRouter({
    platform: process.env.VUE_APP_PLATFORM,  
    routes: [...ROUTES]
});
//Global routing front guard
router.beforeEach((to, from, next) => {
    next();
});
// Global route post guard
router.afterEach((to, from) => {
    console.log('Jump end')
})

export {
    router,
    RouterMount
}

3,main.js import router JS and mount

// main.js

import Vue from 'vue'
import App from './App'
import {router,RouterMount} from './router.js'  //Change the path to your own
Vue.use(router)

App.mpType = 'app'
const app = new Vue({
    ...App
})

//v1.3.5 from H5 end, you should remove the original app$ mount(); Use the rendering method that comes with the route
// #ifdef H5
    RouterMount(app,router,'#app')
// #endif

// #ifndef H5
    app.$mount(); //In order to be compatible with applet and app, it must be written in this way to have effect
// #endif

!! Pay attention to the mounting method of app, which must be implemented according to the writing here!

4. Recompile run

3, Route jump

Method 1: component jump

Vue router can jump through the < router link > < / router link > component. Uni simple router also provides similar components: only this component needs to be registered manually

// main.js
import Mylink from './node_modules/uni-simple-router/dist/link.vue'     
Vue.component('my-link',Mylink)

When registering a component, be careful that the name of the component is not the same as pages The easycom attribute rules in JSON conflict. Otherwise, the component under the easycom path will be found, and an error will be reported if the component is not found.

<!-- adopt path Jump directly and specify jump type -->
<my-link to="/tabbar-4" navType="pushTab">
  <button type="primary">use path Object jump</button>
</my-link>

The complete properties of the component can be found in the document:
Router construction options | uni simple router (hhyang. CN)

Method 2: program navigation:

In the vue example, through this$ The router obtains the routing object (R must be in uppercase). The programmed navigation is very close to vue router, but there are still places to pay attention to. For details, please refer to the documentation

⚠️ Points to note:
In vue projects, name is often used to jump routes. Compared with path, name is more concise and less likely to be changed.

However, you should pay attention to it in uniapp. If you want to use name to jump, you can't carry the query parameter! Similarly, the params parameter cannot be used when using path jump

// The following is the wrong way of writing. name cannot be used with query, and path cannot be used with params parameters
this.$Router.push({ name: 'newsDetail', query: { id: '123' }})
this.$Router.push({ path: '/pages/news/detail', params: { id: '123' }})

// The following is the correct wording:
this.$Router.push({ name: 'newsDetail', params: { id: '123' } })
this.$Router.push({ path: '/pages/news/detail',query: { id: '123' }})

In short: remember: path is used with the query parameter, and name is used with the params parameter

4, APP exit application

When the app routing stack has reached the bottom layer, it is a very common function to click to exit the program again. We can achieve this:

// router.js file

import {
    RouterMount,
    createRouter,
    runtimeQuit
} from './dist/uni-simple-router.js';
// runtimeQuit remember to import

const router = createRouter({
    platform: process.env.VUE_APP_PLATFORM,  
    routerErrorEach:({type,msg})=>{
        console.log({type,msg})
        // #ifdef APP-PLUS
            if(type===3){
                router.$lockStatus=false;
                runtimeQuit();
            }
        // #endif
    },
    routes: [...ROUTES]
});

In routerErrorEach, the meaning of type is as follows:

  • 0 means next(false)
  • 1 means next(unknownType)
  • 2 indicates the locked state and jump is prohibited
  • 3 means that when obtaining the page stack, the page stack is not enough level

In addition to clicking exit again, you can also realize your own logic, such as pop-up prompt exit, etc

const router = createRouter({
    platform: process.env.VUE_APP_PLATFORM,  
    routerErrorEach:({type,msg})=>{
        console.log({type,msg})
        // #ifdef APP-PLUS
            if(type===3){
                router.$lockStatus=false;
                uni.showModal({
                            title: 'Tips',
                            content: 'Are you sure you want to exit the app?',
                            success: function (res) {
                                if (res.confirm) {
                                    plus.runtime.quit();
                                } 
                            }
                        });
            }
        // #endif
    },
    routes: [...ROUTES]
});

5, Route Object

Like Vue router, uniapp can also get the current page routing information in the page, but the initial letter is changed to capital letter:

onLoad() {
    console.log(this.$Route)
}

$Route contains the basic information of Route and Vue config. The fields configured by includes in JS configuration are consistent with the to/from object in the navigation guard. The configuration of permission verification can be realized by using the includes configuration item and navigation guard:

// router.js
router.beforeEach((to, from, next) => {
    if (to.meta && to.meta.power === "public") { // Public page, no login required
        
    } else { // Page to log in
             let isLogin = checkLogin(); // Determine whether to log in
        if (isLogin) {
            next();
        } else {
            next({
                name: "login"
            })
        }
    }
});
// pages.json
"pages": [
        {
            "path": "pages/login/login",
            "name": "login",
            "desc": "Login page",
            "meta": {
                "power": "public" // No login required
            }
        },
          { // Login required
            "path": "pages/my/my",
            "name": "login",
            "desc": "my"
        }
          //...
  ]

Tags: Javascript Vue.js app vue-router uniapp

Posted by Drakla on Mon, 14 Feb 2022 11:35:55 +1030