This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together
preface
Good guy, the reading volume of the Docker operation and maintenance related documents sent yesterday is only 6, so I will continue to update the Vite series of articles today. In the last article, I wrote a back-end interface, but my PC does not have a Java-related environment. Today, I use front-end code to fake login
How do I record login information
- Browser cache Use the browser cache to record user information and token information. You can press F12 to switch to Application and see the browser cache
- Vuex and Pinia are simply state managers. This concept is needed to better manage state outside of components
- Vuex vs. Pinia It is recommended to use Pinia if the function is simple, one is the small size of the package, and two is very easy to get started.
Code implementation
Initialize Pinia
Run the command to download Pinia
yarn add pinia@next
Globally reference Pinana
Introduce Pinia in main.ts with the following core code
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
Copy the code
Create a new store under SRC and create a userinfo.ts with the following content
import { defineStore } from 'pinia'
export const useUserInfoStore = defineStore('userInfo', {
state: () => {
return {
userInfo: {
userName: '',
roleCode: []
}
}
},
actions: {
setUserInfo(userInfo) {
this.userInfo = userInfo
}
}
})
Copy the code
State: s indicates the state of the recorded userInfo type. Actions: Externally developed method that executes to set userInfo to the value passed in. This defines userInfo’s state management
Set the browser cache to record user information
Why would you need a cache after using a state manager? Quite simply, the state manager will fail after pressing F5. If you don’t use caching, pressing F5 will require you to log in again to retrieve user information and so on, which is not reasonable, so use browser caching to record information. Here we use sessionStorage (session cache) to record the cache. Why not use localStorage? Since the cache is always stored in the browser, assuming someone uses your computer and looks up the history to access the corresponding address, they will access all the data you can see without logging in (regardless of the token case). SRC = /cache/index.ts; SRC = /cache/index.ts
/** * window. LocalStorage Permanent cache * @method set Set permanent cache * @method get get permanent cache * @method remove remove permanent cache * @method clear */ export const Local = {// set(key: string, val: string) const Local = { Any) {window. LocalStorage. SetItem (key, JSON stringify (val)}, / / to get permanent cache the get (key: string) {let JSON: Any = window. LocalStorage. The getItem (key) return JSON. Parse (JSON)}, / / remove persistent cache remove (key: string) { window.localStorage.removeItem(key) }, / / remove all permanent cache the clear () {window. LocalStorage. The clear ()}} / * * * window. The temporary sessionStorage browser cache * * @ @ method set set up temporary cache method * @method remove * @method clear Remove all temporary caches */ export const Session = {// Set temporary caches set(key: String, val: any) {window. The sessionStorage. SetItem (key, JSON stringify (val)}, / / to get a temporary cache the get (key: string) {let JSON: Any = window. The sessionStorage. The getItem (key) return JSON. Parse (JSON)}, / / remove the temporary cache remove (key: String) {window. The sessionStorage. RemoveItem (key)}, / / to remove all temporary cache the clear () {window. The sessionStorage. The clear ()}}Copy the code
In case you need to use local cache, I’m going to use local cache as well
Redesign the login page
I only put the core code here, write the implementation logic, if you are interested in my Git project to get the source code
Import {Session} from '@/utils/cache/index' import {useUserInfoStore} from '@/stores/userInfo'... import {Session} from '@/utils/cache/index' import {useUserInfoStore} from '@/stores/userInfo'... Const handleLogin = () => {loginref.value.validate ((vaild) => {if (vaild) {// Set the interface loginload.value = true to prevent repeated calls during loading Session.set('token', new Date().getTime()) let username = loginModel.username ? loginModel.username : '' let userInfo = { userName: '', roleCode: [] as any[] } switch (username) { case 'admin': userInfo = getAdminInfo(username) break case 'dept': userInfo = getDeptAdminInfo(username) break default: userInfo = getCommonUserInfo(username) break } Session.set('userInfo', userInfo) userInfoStore.setUserInfo(userInfo) setRouteStoreByUserCode(userInfo.roleCode) loginLoad.value = false Router.push ('/')}})} // Admin user information const getAdminInfo = (userName) => {let userInfo = {userName, roleCode: [ 'system', 'system-user', 'system-setting', 'system-user:add', 'system-user:update', 'system-user:search']} return userInfo} // Department head user const getDeptAdminInfo = (userName) => {let userInfo = { userName, roleCode: [ 'system', 'system-user', 'system-user:add', 'system-user:update', 'system-user:search']} return userInfo} // Common user information const getCommonUserInfo = (userName) => {let userInfo = { userName, roleCode: [] } return userInfo }Copy the code
This mimics the user information obtained after requesting the interface. Note that it is stored in the Session first and then in the state manager
Handle invalid values using the status manager after refreshing
When designing to display user information on Layout, you will find that pressing F5 retrieves the default value of the status manager. We get it from the cache before we jump and then we set it up. Here’s the code
router.beforeEach((to, _from, Next) => {let path = to.path // Whitelist does not validate token and permission if (whitenamerouters.indexof (path) > -1 && path! = '/') {return next()} // Other routes if no token jump to login page let token = session.get ('token') if (! Token) {elmessage. warning(' Please login first! ') return next('/login')} // Anti-refresh let userInfoStore = useUserInfoStore() setUserStore(userInfoStore) let needRoleCode = "If (to.meta && to.meta. RoleCode) {needRoleCode = to.meta. RoleCode as string} // If the current path does not require permissions, perform the jump if (needRoleCode = = = '| |! needRoleCode) { return next() } let roleCodeArr: string[] = userInfoStore.userInfo.roleCode roleCodeArr = userInfoStore.userInfo.roleCode if (! roleCodeArr || roleCodeArr.length === 0) { return next('/login') } if (roleCodeArr! .indexof (needRoleCode) > -1) {return next()} else {return next('/login')}}) // To prevent loss of user information when refreshing const setUserStore = (userInfoStore) => { let userInfo = userInfoStore.userInfo if (! userInfo || ! userInfo.userName) { userInfoStore.setUserInfo(Session.get('userInfo')) } }Copy the code
I have part of the route authentication code here. Because I set userInfo’s default userName to be an empty string, I need to check if it’s empty.
conclusion
Through this article, I can find that Pinia is actually very simple to use, and it has been realized to record user information. Ready to start rendering routes. Different roles see different directories. Please follow my nuggets account :juejin.cn/user/261290… Welcome to star my Git project :gitee.com/liangminghu… Next period: dynamic rendering route implementation and encountered pits