This time I will bring you the implementation method of Vue authorized login. What are the precautions for Vue authorized login? 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.
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 theroute 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:Quick implementation of array deduplication method in PHP
Detailed explanation of JS callback function use cases
The above is the detailed content of Vue authorization login implementation method. For more information, please follow other related articles on the PHP Chinese website!

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.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function