


A brief discussion on how to ensure that each page of the mini program is logged in
Dec 27, 2021 am 10:23 AMHow does the WeChat applet ensure that every page has been logged in? This article will introduce you to the method of mini program to ensure that every page is logged in. I hope it will be helpful to you!
In a WeChat applet, there is a home page, a personal page, some list pages, detail pages, etc. Most of these pages can be shared. When the shared page is opened by another user, how does this page ensure that the user is logged in?
There are many solutions on the Internet that add an interception to the request encapsulation. If there is no token, first call the login request to obtain the token, and then continue. There is nothing wrong with this solution. Just pay attention to one thing. When multiple requests are triggered on a page at the same time, after all requests are intercepted, they are placed in an array. After successfully obtaining the token, just traverse the array one request at a time.
But this requirement is a little more complicated. For example, chain convenience store applet, most pages need to have a store (because it is necessary to obtain the inventory, price, etc. of the current store products based on the store). This store is based on the current store. Positioning is obtained by calling the background interface. At this time, it would be too troublesome to encapsulate it in the request.
Solution
First of all, we noticed that logging in, getting the position and our page request are asynchronous, we need to ensure that the page request It is after logging in and obtaining positioning, but if we write it again for every page, the maintainability will be too poor. So we can extract a way to do this. So the code is like this:
const app = getApp() Page({ data: { logs: [] }, onLoad() { app.commonLogin(()=>{ // 處理頁頁面請求 }) } })
Doing this seems to solve our problem, but think about it again, if you want to do more, such as unified processing of onShareAppMessage for each page, but I I don’t want to write it again on every page. In addition, I want to implement a watch for each page myself. How to do it?
Further solution
We can see that the WeChat applet, each page is a Page(), then we can give this Page Adding a layer of shell outside, we can have a MyPage to replace this Page. Without further ado, here is the code:
tool.js Related code
/** * 處理合并參數(shù) */ handlePageParamMerge(arg) { let numargs = arg.length; // 獲取被傳遞參數(shù)的數(shù)值。 let data = {} let page = {} for (let ix in arg) { let item = arg[ix] if (item.data && typeof (item.data) === 'object') { data = Object.assign(data, item.data) } if (item.methods && typeof (item.methods) === 'object') { page = Object.assign(page, item.methods) } else { page = Object.assign(page, item) } } page.data = data return page } /*** * 合并頁面方法以及數(shù)據(jù), 兼容 {data:{}, methods: {}} 或 {data:{}, a:{}, b:{}} */ mergePage() { return this.handlePageParamMerge(arguments) } /** * 處理組件參數(shù)合并 */ handleCompParamMerge(arg) { let numargs = arg.length; // 獲取被傳遞參數(shù)的數(shù)值。 let data = {} let options = {} let properties = {} let methods = {} let comp = {} for (let ix in arg) { let item = arg[ix] // 合并組件的初始數(shù)據(jù) if (item.data && typeof (item.data) === 'object') { data = Object.assign(data, item.data) } // 合并組件的屬性列表 if (item.properties && typeof (item.properties) === 'object') { properties = Object.assign(properties, item.properties) } // 合組件的方法列表 if (item.methods && typeof (item.methods) === 'object') { methods = Object.assign(methods, item.methods) } if (item.options && typeof (item.options) === 'object') { options = Object.assign(options, item.options) } comp = Object.assign(comp, item) } comp.data = data comp.options = options comp.properties = properties comp.methods = methods return comp } /** * 組件混合 {properties: {}, options: {}, data:{}, methods: {}} */ mergeComponent() { return this.handleCompParamMerge(arguments) } /*** * 合成帶watch的頁面 */ newPage() { let options = this.handlePageParamMerge(arguments) let that = this let app = getApp() //增加全局點擊登錄判斷 if (!options.publicCheckLogin){ options.publicCheckLogin = function (e) { let pages = getCurrentPages() let page = pages[pages.length - 1] let dataset = e.currentTarget.dataset let callback = null //獲取回調(diào)方法 if (dataset.callback && typeof (page[dataset.callback]) === "function"){ callback = page[dataset.callback] } // console.log('callback>>', callback, app.isRegister()) //判斷是否登錄 if (callback && app.isRegister()){ callback(e) } else{ wx.navigateTo({ url: '/pages/login/login' }) } } } const { onLoad } = options options.onLoad = function (arg) { options.watch && that.setWatcher(this) onLoad && onLoad.call(this, arg) } const { onShow } = options options.onShow = function (arg) { if (options.data.noAutoLogin || app.isRegister()) { onShow && onShow.call(this, arg) //頁面埋點 app.ga({}) } else { wx.navigateTo({ url: '/pages/login/login' }) } } return Page(options) } /** * 合成帶watch等的組件 */ newComponent() { let options = this.handleCompParamMerge(arguments) let that = this const { ready } = options options.ready = function (arg) { options.watch && that.setWatcher(this) ready && ready.call(this, arg) } return Component(options) } /** * 設(shè)置監(jiān)聽器 */ setWatcher(page) { let data = page.data; let watch = page.watch; Object.keys(watch).forEach(v => { let key = v.split('.'); // 將watch中的屬性以'.'切分成數(shù)組 let nowData = data; // 將data賦值給nowData for (let i = 0; i < key.length - 1; i++) { // 遍歷key數(shù)組的元素,除了最后一個! nowData = nowData[key[i]]; // 將nowData指向它的key屬性對象 } let lastKey = key[key.length - 1]; // 假設(shè)key==='my.name',此時nowData===data['my']===data.my,lastKey==='name' let watchFun = watch[v].handler || watch[v]; // 兼容帶handler和不帶handler的兩種寫法 let deep = watch[v].deep; // 若未設(shè)置deep,則為undefine this.observe(nowData, lastKey, watchFun, deep, page); // 監(jiān)聽nowData對象的lastKey }) } /** * 監(jiān)聽屬性 并執(zhí)行監(jiān)聽函數(shù) */ observe(obj, key, watchFun, deep, page) { var val = obj[key]; // 判斷deep是true 且 val不能為空 且 typeof val==='object'(數(shù)組內(nèi)數(shù)值變化也需要深度監(jiān)聽) if (deep && val != null && typeof val === 'object') { Object.keys(val).forEach(childKey => { // 遍歷val對象下的每一個key this.observe(val, childKey, watchFun, deep, page); // 遞歸調(diào)用監(jiān)聽函數(shù) }) } var that = this; Object.defineProperty(obj, key, { configurable: true, enumerable: true, set: function (value) { if (val === value) { return } // 用page對象調(diào)用,改變函數(shù)內(nèi)this指向,以便this.data訪問data內(nèi)的屬性值 watchFun.call(page, value, val); // value是新值,val是舊值 val = value; if (deep) { // 若是深度監(jiān)聽,重新監(jiān)聽該對象,以便監(jiān)聽其屬性。 that.observe(obj, key, watchFun, deep, page); } }, get: function () { return val; } }) }
Page code:
app.tool.newPage({ data: { // noAutoLogin: false }, onShow: function () { // 在這里寫頁面請求邏輯 } }
Finally
The code has been running online for a long time. You can add it according to your needs through the newPage package in the tool. In short, I am here to provide an idea. If you have a better idea, please share it.
[Related learning recommendations: 小program development tutorial]
The above is the detailed content of A brief discussion on how to ensure that each page of the mini program is logged in. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

This article brings you some related issues about WeChat mini programs. It mainly introduces how to use official account template messages in mini programs. Let’s take a look at them together. I hope it will be helpful to everyone.

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Geolocation positioning and map display of PHP and mini programs Geolocation positioning and map display have become one of the necessary functions in modern technology. With the popularity of mobile devices, people's demand for positioning and map display is also increasing. During the development process, PHP and applets are two common technology choices. This article will introduce you to the implementation method of geographical location positioning and map display in PHP and mini programs, and attach corresponding code examples. 1. Geolocation in PHP In PHP, we can use third-party geolocation
