Home Web Front-end JS Tutorial Analysis of Vuex management login status

Analysis of Vuex management login status

Dec 22, 2017 am 09:48 AM
vuex analyze state

This article mainly introduces the detailed explanation of Vuex management login status. After reading the vuex document carefully, it is still unclear, but at least I understand that it is a specialized management status. According to the change of data status, the view update can be driven. Since Well, at least logging in and registering is a state. Just use logging in for testing and learning vuex. But having said that, since it is dedicated to managing states, I at least have to carefully consider the state logic of this learn learning project.

1. It is said that the status in the stored vuex store is temporary. Right-click to refresh the page and these statuses will be destroyed (this is said to be true. I have no idea if you can ask someone to clarify. Method to confirm), if this is the case, my user status user should still be written to sessionStorage, otherwise the logged in user will become not logged in as soon as the page is refreshed, and the user will go crazy. Therefore, the user status in the store should be read from sessionStorage.

2. Among the existing pages in this learn project, home, paroducts, FAQ, login, and regin should be accessible without logging in, while manger and the sub-pages below manger are required. You need to log in to access.

3. The more special ones are login and regin. If the user is already logged in, it is possible to access these two pages again. However, if the user is already logged in, then use another account. Let's log in once. It is obviously unreasonable that there are 2 user data in sessionStorage. Therefore, it should be stipulated that if the user is already logged in and accesses login or regin, then we should first remove the user data in sessionStorage

4. Vuex stipulates that all state changes can only rely on mutations, and actions can only drive mutations to change states. In this project, the login status will only change in three situations: login, registration and logout. When the login and registration are successful, an action for which the user exists will be executed, and when the user logs out, an action for which the user does not exist will be executed.

5. Vuex official also mentioned a getter thing. I feel that it should be when we need to access the state in the store. To be precise, it should be after taking out the state and giving it to the state. It is used to make some processing changes, and it should only be gettered once. If there are too many, it will feel messy (I don’t know if this idea is correct), but when I saw this.$store.getters.doneTodosCount written like this, I feel that it should be able to be used more than once. Bundle. I guess I've thought a little too much, and it doesn't seem to be useful at the moment. Maybe I need to experience the required application scenarios before I can fully understand it.

6. There is another module. This one is a bit confusing. I don’t understand it very well, so I won’t care about it for now.

It is expected that the login status of the store should come from sessionStorage. Take it, so I first constrain the routing. Which pages require user and which do not. To access those pages, you need to remove user

Open main.js

Add code


// 这个官方名字叫导航守卫,挺形象的
router.beforeEach((to, from, next) => {
 // 如果是去登录或注册,那就先把user移除
 if (to.path === '/login' || to.path === '/regin') {
  sessionStorage.removeItem('user')
 }
 let user = JSON.parse(sessionStorage.getItem('user'))
 if (!user && (to.path === '/manger/my' || to.path === '/manger/send' || to.path === '/manger/history')) {
  next({ path: '/login' })
 } else {
  next()
 }
})
Copy after login

It feels weird to write it like this. I wonder if there is a simpler way to write it?

But the desired effect can be achieved

Then try to write the store

Write a basic structure first


Then write it down step by step

Does it mean that this requires a function?

Oh, that’s not right , I’m stupid, this is assignment (I don’t know if the assignment is accurate), it’s not writing an obj object, no comma is needed

store.js


import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 创建基本状态
const state = {
 // 登录状态为没登录
 logined: false,
 // 用户信息数据,目前只需要avatar和name,还是把username也加上吧
 LoginedUser: {
  name: '',
  avatar: '',
  username: ''
 }
}
// 创建改变状态的方法
const mutations = {
 // 改变状态的方法也需要2个,一个是登录或注册了,一个是登出了
 // 这里不能写箭头函数???
 // 登录
 LOGIN (state) {
  // 先让登录状态变为登录了
  state.logined = true
  // 然后去sessionStorage取用户数据
  let user = JSON.parse(sessionStorage.getItem('user'))
  // 再把用户数据发下去
  state.LoginedUser.name = user.name
  state.LoginedUser.avatar = user.avatar
  state.LoginedUser.username = user.username
 },
 // 登出
 LOGOUT (state) {
  // 这个同理
  state.logined = false
  state.LoginedUser.name = ''
  state.LoginedUser.avatar = ''
  state.LoginedUser.username = ''
 }
}
// 创建驱动actions可以使得mutations得以启动
const actions = {
 // 这里先来一个驱动LOGIN的东西就叫login吧
 // 这个context是官方写的,应该叫什么无所谓
 login (context) {
  context.commit('LOGIN')
 },
 // 同样来个logout
 logout (context) {
  context.commit('LOGOUT')
 }
}

export default new Vuex.Store({
 state,
 mutations,
 actions
})
Copy after login

I think this should be enough, I still need to test it

If not, you should also hang the action where it should be, and then reference the store status. Where the store data is referenced

First go to the login page to hang the action

It should be like this, the same is true for registration

Then there is the logout page

header.vue

At the same time, we are not creating the page Fetching data from sessionStorage

There is also a main.js

It would be really troublesome if it cannot take effect in main.js, just imagine , the logged-in user goes directly to the /login page. The user data in seeionStorage is cleared, but the data in the store is not updated. Then there is still an avatar hanging on the head???

There is one more step to obtain Data in the store

header.vue

Let’s test it quickly

I cried...just four mistakes

I followed the official What you said is written

Comment out the data in header.vue, there is still an error

But this What does "dispatch" mean "undefined"? I just followed it as written. Could you please help me figure it out?

Changing dispatch to context won't work either

Change to commit and give it a try

I still feel bad, let me check the information again

I have been studying for a long time Solved part of the problem

First of all, I wrote the action in store.js like this


But I think the original way of writing is not wrong either

Then I commented out this sentence in main.js


Then it was normal, dispatch was correct, so what I was worried about Sure enough, it happened

Go to log in first


##You can see that the upper right corner of the header has indeed immediately changed to The user information meets the requirements. However, if I go to the address bar and enter /login



##, it jumps to login. page, but the avatar is really still hanging in the upper right corner..., indicating that there is still login data in the store. Although if you think about it carefully, this has no impact. If he logs in successfully again, the data will naturally It has changed, and generally no one will visit the login page like this, but I feel that this is wrong.

And I think there should be a way to write the distribution of this action in main.js. I wonder if anyone can give me some advice!

Related recommendations:


vuex concept understanding and practical tutorial

About Vuex 2.0 of Vue.js 2.0 You need to update Knowledge base

Build a note-taking application with Vuex_html/css_WEB-ITnose

The above is the detailed content of Analysis of Vuex management login status. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Connection status in standby: Disconnected, reason: NIC Compliance Connection status in standby: Disconnected, reason: NIC Compliance Feb 19, 2024 pm 03:15 PM

"The connection status in the event log message shows Standby: Disconnected due to NIC compliance. This means that the system is in standby mode and the network interface card (NIC) has been disconnected. Although this is usually a network issue , but can also be caused by software and hardware conflicts. In the following discussion, we will explore how to solve this problem." What is the reason for standby connection disconnection? NIC compliance? If you see the "ConnectivityStatusinStandby:DisConnected,Reason:NICCompliance" message in Windows Event Viewer, this indicates that there may be a problem with your NIC or network interface controller. This situation is usually

How to set Momo status How to set Momo status Mar 01, 2024 pm 12:10 PM

Momo, a well-known social platform, provides users with a wealth of functional services for their daily social interactions. On Momo, users can easily share their life status, make friends, chat, etc. Among them, the setting status function allows users to show their current mood and status to others, thereby attracting more people's attention and communication. So how to set your own Momo status? The following will give you a detailed introduction! How to set status on Momo? 1. Open Momo, click More in the lower right corner, find and click Daily Status. 2. Select the status. 3. The setting status will be displayed.

How to implement data statistics and analysis in uniapp How to implement data statistics and analysis in uniapp Oct 24, 2023 pm 12:37 PM

How to implement data statistics and analysis in uniapp 1. Background introduction Data statistics and analysis are a very important part of the mobile application development process. Through statistics and analysis of user behavior, developers can have an in-depth understanding of user preferences and usage habits. Thereby optimizing product design and user experience. This article will introduce how to implement data statistics and analysis functions in uniapp, and provide some specific code examples. 2. Choose appropriate data statistics and analysis tools. The first step to implement data statistics and analysis in uniapp is to choose the appropriate data statistics and analysis tools.

How to check server status How to check server status Oct 09, 2023 am 10:10 AM

Methods to view server status include command line tools, graphical interface tools, monitoring tools, log files, and remote management tools. Detailed introduction: 1. Use command line tools. On Linux or Unix servers, you can use command line tools to view the status of the server; 2. Use graphical interface tools. For server operating systems with graphical interfaces, you can use the graphics provided by the system. Use interface tools to view server status; 3. Use monitoring tools. You can use special monitoring tools to monitor server status in real time, etc.

Detailed explanation of the five states of Java threads and state transition rules Detailed explanation of the five states of Java threads and state transition rules Feb 19, 2024 pm 05:03 PM

In-depth understanding of the five states of Java threads and their conversion rules 1. Introduction to the five states of threads In Java, the life cycle of a thread can be divided into five different states, including new state (NEW), ready state (RUNNABLE), Running status (RUNNING), blocking status (BLOCKED) and termination status (TERMINATED). New state (NEW): When the thread object is created, it is in the new state. At this point, the thread object has allocated enough resources to perform the task

Case analysis of Python application in intelligent transportation systems Case analysis of Python application in intelligent transportation systems Sep 08, 2023 am 08:13 AM

Summary of case analysis of Python application in intelligent transportation systems: With the rapid development of intelligent transportation systems, Python, as a multifunctional, easy-to-learn and use programming language, is widely used in the development and application of intelligent transportation systems. This article demonstrates the advantages and application potential of Python in the field of intelligent transportation by analyzing application cases of Python in intelligent transportation systems and giving relevant code examples. Introduction Intelligent transportation system refers to the use of modern communication, information, sensing and other technical means to communicate through

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

See all articles