How to implement on-demand authorized login for Vue WeChat project
This time I will bring you how to implement VueWeChat projectOn-demand authorization login, what are the precautions of implementing on-demand authorization login on Vue WeChat project, the following is a practical case, Let’s take a look.
The project uses Vue as the development framework. There are two situations when users browse the page:
One requires users to log in before they can continue browsing;
The other is that users can browse at will without logging in.
Pages that do not require user login may contain operations that require user information. In this case, the user needs to log in before subsequent operations can be performed. Therefore, authorization login policies need to be distinguished.
Thinking
1. Generally speaking, the H5 page we develop for WeChat requires authentication when entering the page, requiring the user to You must log in to continue browsing. However, due to product requirements, for this project we need to divide the authentication strategies of different pages and design them according to general and special:
2. In general, users are required to authorize login as soon as they enter the page. According to the routine WeChat authorized login process. After logging in, the user continues browsing.
3. In special cases, configure a whitelist for pages that do not require user login. Just enter the route that exists in the whitelist and do not enter the function that detects user login status , render the page directly.
For operations that require user information when the user is not logged in, according to my current understanding, even if it is a silent authorization based on WeChat, the page must be refreshed, and it is impossible to achieve truly senseless authorization and continue the user operation. Therefore, I chose to give the user a more friendly prompt at the front-end level to let the user understand the authorization process. The disadvantage is that the previous operation only triggered the authorized login. After the authorized login, the user needs to perform the operation again.
// routerRule.js export default function routerRule (router, whiteList = []) { // other codes... router.beforeEach( (to, from, next ) => { // 因为授权登录涉及异步操作,因此使用promise,成功的回调中调用next函数 new Promise((resolve, rejects) => { if ( whiteListRouter.indexOf(to.path) !== -1 ) { resolve() return } // 常规页面授权登录过程 if (hasToken()) { // codes,获取用户信息并且跳转所需跳转的页面 } else { // 判断用户是否已经进行微信授权 if (hasAuthed()) { // 进行过微信授权之后,重定向回来的url中包含了微信的授权信息,可以将url上截取的参数发送到服务器,换取用户的token,随后进入上述有token时候的步骤 getWechatUserInfo().then(res => { resolve() }) } else { // 用户尚未进行微信授权,则调用微信授权的方法,进行授权登录。 getWechatAuth() } } }).then( res => { next() }) }) router.afterEach(( to, from ) => { wxShare({ title: to.meta.title, desc: to.meta.shareDesc, link: to.meta.shareLink, logo: to.meta.shareLogo}) }) }
This project is to bind the user's WeChat information with the user information of this site when the user first binds to WeChat. Therefore, after obtaining the user's WeChat authorization information, the user can be obtained token to obtain the user’s other user information on this site.
Processing operations that require permissions without logging in to the page
According to the above logic, after entering the whitelist, the entire function has been If you return it, you will not enter the following authentication process. However, if you perform operations that require permissions on such a page, you need to trigger the authorization login process, and after authorization, user information must be obtained together.
// checkLogin.js export function checkLogin({ redirectUrl, wxAuthLoading, wxAuthLoaded, callback } = {}) { if (getToken()) { // ... callback && callback() } else { // 提示用户正在授权中 wxAuthLoading && wxAuthLoading() getWechatAuth( redirectUrl || window.location.href ).then( res => { // 授权完毕,提示用户授权成功 wxAuthLoaded && wxAuthLoaded() }) } }
At the same time, we need to add some operations to the routing whitelist
// routerRule.js export default function routerRule (router, whiteList = []) { // other codes... router.beforeEach( (to, from, next ) => { // 因为授权登录涉及异步操作,因此使用promise,成功的回调中调用next函数 new Promise((resolve, rejects) => { if ( whiteListRouter.indexOf(to.path) !== -1 ) { // 如果已经进行微信授权但是没有token值的,就调用以下函数获取token值 if ( !hasToken() && hasAuthed() ) { getWechatUserInfo().then(res => { resolve() }) } resolve() return } // 常规页面授权登录过程 if (hasToken()) { // codes,获取用户信息并且跳转所需跳转的页面 } else { // 判断用户是否已经进行微信授权 if (hasAuthed()) { // 进行过微信授权之后,重定向回来的url中包含了微信的授权信息,可以将url上截取的参数发送到服务器,换取用户的token,随后进入上述有token时候的步骤 getWechatUserInfo().then(res => { resolve() }) } else { // 用户尚未进行微信授权,则调用微信授权的方法,进行授权登录。 getWechatAuth() } } }).then( res => { next() }) }) // other codes... }
Pits and imperfections
1. In this solution, after user authorization, user information must be obtained before routing jump, otherwise the WeChat authorization information on the URL will be lost and obtaining user information will fail.
2. The disadvantage of this solution is that the developer needs to add checkLogin to all operations that require permissions on the login-free page. Since this permission-requiring operation generally involves sending asynchronous requests, if you do not consider reducing unnecessary asynchronous requests, you can set an interceptor on the request method to determine the code returned by the backend. If the returned code is If the user has not logged in to the code, WeChat authorization will be performed. This approach is more convenient in the development process, but it will send some unnecessary requests to the backend when the user is not logged in, which is not good.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Vue project is packaged and sent to the server
JS implements simple shopping cart function code analysis
The above is the detailed content of How to implement on-demand authorized login for Vue WeChat project. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor