preface

Our small program is developed by uni-App. Uni-app is vUE style, so it is very efficient to develop. However, there is a defect that there is no routing hook, which is quite inconvenient. Generally speaking, one of the most common application scenarios of routing hooks is permission verification, and we have a lot of pages that need permission verification, so we also encountered this problem in development.

The original plan

In fact, it is very simple. Some pages need to be logged in before they can enter, that is, they have a token to enter, otherwise they have to log in before they can enter.

Therefore, before this, our approach is to determine whether there is a token or not every time we jump to the page that requires permission. If there is, we will enter, and if there is not, we will go to the login page

BindTap: function(e) {if(! NavigateTo ({url: 'login'}) return} uni. NavigateTo ({url: 'detail? id=123' }) }Copy the code

There is no problem with doing this, it is too troublesome, every page that needs permission must be judged first, if the page is much, it really dare not think about it, and it is not easy to maintain. If there is a routing hook, it will be very convenient.

implementation

Since there is no UNIAPP and no routing hook, we can extend it ourselves

const methodToPatch = ['navigateTo', 'redirectTo', 'switchTab', 'navigateBack'] methodToPatch.map(item => { const original = uni[item] // uni[item] = function(opt = {}, needAuth) { if (needAuth && ! NavigateTo ({url: '/login'})} else {return original.call(this, opt)}}})Copy the code

Is not very simple, with this extension, it will be convenient to use later

Function (e) {uni. NavigateTo ({url: 'detail? id=123' }, true) }Copy the code

(PS: In fact, the idea of this extension is just a while ago when I was reading the source code of Vue, I saw its array processing, and then borrowed its extension idea, and later checked the information and found that this is actually the decorator mode)

Still want to learn to learn excellent code, maybe one day can use for reference, ha ha ha

Vue extension array source point this

Finished ~