Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the process of login status management in a vuex project

2025-04-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you what the login status management process is like in the vuex project. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Tools:

Chorme browser installs Vue.js devtools to facilitate debugging

Login scenario:

The navigation or other places on the page sometimes show the user's current login status, which can be divided into: not logging in, logging in (loading), logging in successfully and displaying the user name.

Some pages can be viewed by users without logging in, but some pages must be logged in to enter.

Practice:

Scenario 1 thinking and practice

Create a data warehouse with vuex

/ / create a new store directory under the src directory, and create an index.js as follows / / create a data warehouse import Vuex from 'vuex';import vue from' vue' Import loginUser from 'loginUser.js'Vue.use (Vuex) const store = new Vuex.Store ({modules: {/ / modules can put different states in a single object loginUser / / whether or not you are logging in}, strict: true, / / only allowed to change the state through mutations})

Set login status loading and current login user user

/ / create a loginUser.js Create the status state that his state/mutations/actions// needs to maintain: {loading: false, / / login status user: null, / / currently logged in user} / / calculation attribute getters: {status (state) {if (state.loading) {return 'loading'} else if (state.user) {return' login'} else {return 'unLogin'} / / change loading and user status mutations: {/ / set loading setLoading (state, msg) {state.loading = msg}, / / set user setUser (state, msg) {state.user = msg}}, / / submit the status of change in actions actions: {/ / login method ctx is equivalent to store async login (ctx) Msg) {/ / login status is set to true ctx.commit ("setLoading", true) const result = await xxxapi.login (msg.loginId, msg.loginPassword) if (result) {/ / login successful ctx.commit ('setUser') Result) / / after a successful login, set the login status to false ctx.commit ('setLoading', false)} / / return whether the login is successful return result}, / / determine whether you have logged in to async isLogin (ctx) {/ / logging in to ctx.commit (' setLoading') True) / / whether the interface is logged in const result = await xxxapi.isLogin () Ctx.commit ('setUser', result); ctx.commit (' setLoading', false)}, / / log out of async logout (ctx) {ctx.commit ('setLoading', false) await xxxapi.logout (); ctx.commit (' setUser', null); ctx.commit ('setLoading', false)}}

The page uses:

When logging in, there is a login button, and the status of the button can be obtained from the Vuex warehouse.

{{loading? 'loading...':' login'} computed: {/ / encapsulate loading in computed instead of writing this.$store.state.loginUser pile / / loading () {/ / return this.$store.state.loginUser.loading every call / / optimize / / Auxiliary function / / import {mapState} from "vuex"... mapState ({loading: (state) = > state.loginUser.loading})}

Distribute action when you submit when you click the button

Async handleSubmit () {const result = await this.$store.dispatch ("loginUser/login", {loginId: this.loginId, loginPassword: this.loginPassword}); if (result) {/ / login successful route jump const path = this.$route.query.url | |'/ 'this.$router.push (path)}}

Toggle the login status at this time in the navigation of the page [loading/login/unlogin]

Please wait a moment while you are logging in. The current login user {{user.name}} logs out to computed: {. MapGetters ("loginUser", ["status"]),... mapState ("loginUser", ["user"]),}

Change the status when you log out

Async handleLogout () {await this.$store.dispatch ("loginUser/logout") / / Jump to the landing page this.$route.push (/ xxx)}. Each page refresh needs to check the login status, which is judged in main.js, that is, when the vue is created. Thinking and practice of store.dispatch ('loginUser/isLogin') scenario 2

Referenced the permission settings in the background project

Overall design:

After refreshing the page, check the login status at this time in the Vuex repository-> Navigation Guard (router.beforeEach) check whether the page is determined by the parameters set in meta

You need to log in before you can view the-> page rendering.

Overall logic:

1. When entering the page, determine whether the page needs to be logged in to view.

two。 Determine the login status. There are three states as follows:

If you are already logged in, go directly to the page you want to go to.

If you are not logged in, go to the login page and let the user log in.

If the status is loading, pass in the path of the page you want to go to, and monitor the changes of user login status in the Vuex repository in the loading page. After the monitoring status changes, either you are already logged in or there is no login status, and then go to step 1 to determine whether you want to log in.

Practice:

Set meta in router. If auth is true, you need to log in to access it.

/ / import Home from ". / xx/xx.vue" export default in routes.js [{path: "/ home", component:Home, meta: {auth: true, / / pages that need permission to access}}] set the routing guard router.beforeEach ((to, from) in index.js Next) = > {if (to.meta.auth) {/ / login permission is required to access const result = store.getters ["loginUser/status"] if (result = = 'loading') {/ / load status I don't know if there is a login / jump to a login page, and monitor whether the login has been successful in the page, otherwise it will stay here forever / / and record where you came from before the route jump. Otherwise, I don't know which page next ({path:'/ loading') to jump to. / / go to the page of [logging in] query: {url: to.fullpath}})} else if (result = = 'login') {/ / login succeeded in next () } else {/ / did not log in to this.$message.info ('you need to log in') Next ({path:'/ login', / / go to the page [logging in] query: {url: to.fullpath}})} else {/ / the page next ()}} that can be accessed without login permission)

Monitor the status at this time on the logining [logging in] page

Created () {this.unWatch = this.$watch (()) = > this.$store.getters ["loginUser/status"], (status) = > {console.log ('status at this time', status) If (status! = = 'loading') {this.$router.push (this.$route.query.url | |' / home'). Catch (() = > {}, {immediate: true})}, destroyed () {/ / unmonitor this.unWatch ()} the above is what the login status management process is like in the vuex project. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report