search
HomeWeb Front-endJS TutorialAnalysis of Vuex management login status

Analysis of Vuex management login status

Dec 22, 2017 am 09:48 AM
vuexanalyzestate

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()
 }
})

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
})

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
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor