Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
The small program does not have the same route interception function as vue-router, so you need to manually implement, the following is to share the specific implementation method for your reference.
The implementation roadmap is the same as that of vUE. Define a global token variable. When entering a page, check whether the token exists.
Create a tool folder, create a phones. js, and encapsulate the code for routing interception as follows:
// routers.js
export function routerFillter(pageObj) {
let _onShow = pageObj.onShow;
pageObj.onShow = function() {
const token = getApp().globalData.token;
if (token && token.length > 0) {
// There is login information - page open
let currentInstance = getPageInstance();
_onShow.call(currentInstance, options);
} else {
// No login information - Login
wx.switchTab({
url: '/pages/user/user'}}})return Page(pageObj);
}
Copy the code
To import the blocking method into the page to be blocked, use the following provisioning:
// index.js
import { routerFillter } from ".. /.. /utils/routers";
routerFillter({ // routerFillter replaces the original Page
// Normal logical writing
data: {},
methods: {},... })Copy the code
This is a simple route interception function.