[vue3+pinia+Cookie] Realize token login and data persistence

The vue2 background login project is basically vuex+local storage or vuex+cookie or vuex+a library specially used to persist vuex, such as: vuex-persistedstate

By default, vuex saves the state of the application in the client memory. When the page is refreshed, the data in memory will be lost, resulting in the loss of data in vuex. Because the state storage of vuex is temporary and will not be persisted to local storage or server.

So it is not enough to rely on vuex alone when logging in, and the data needs to be persisted.

** The same is true in vue3, this article uses pinia+Cookie

Pinia, like vuex, is the official state management library of vue.js, which is used to manage the state (data) of the application, centralized state management, data sharing between components, better responsive features, support for expansion and development, and convenient debugging tools .

A cookie is a small file that transfers data between the client (browser) and the server. It is usually set by the server in the HTTP response and stored in the browser. The browser sends the cookie back in subsequent requests. server.
Cookies are mainly used to store and transmit some data about the interaction between users and websites, such as user preferences, login information, shopping cart contents, etc. They can be used to maintain state between different requests so that websites can identify users And provide a personalized experience .
There is a mechanism similar to cookies, and the mechanism used to transfer data between the client and the server is:
1. Session Storage (session storage), the data is only valid during the current session, and the data is only retained before the browser closes the window
2 , Local Storage (local storage), the data is persistent between different sessions, and will only be removed when the user explicitly clears the browser cache or deletes it through code 3, web Storage (web storage), Web Storage is
Session The general term for Storage and Local Storage. It includes two mechanisms, Session Storage and Local Storage, which provide the ability to store data on the client.
4. IndexedDB (indexed database), IndexedDB is an API that stores structured data on the client side. It provides a database-like environment to create and manage databases in the browser to store and retrieve large amounts of data. Unlike Cookie, IndexedDB can store more complex data types and provide more advanced data query and indexing functions. Speaking of
Cookie, a Cookie mainly contains the following attributes:
Name: the name or key of the Cookie, Used to identify cookies.
Value (Value): The specific data value associated with the cookie.
Domain: Specifies the domain name where the cookie is available. By default, a cookie is only available under the domain it was created on and its subdomains.
Path (Path): Specify the path where the cookie is available. By default, a cookie is only available under the path of the page that created it.
Expiration time (Expires): Specify the expiration time of the cookie. Once expired, the browser will no longer send the cookie.
Cookie workflow:
The client (browser) sends a request to the server.
The server sets a cookie in the HTTP response.
The browser receives the HTTP response and stores the cookie locally.
On subsequent requests, the browser sends the cookie to the server.
The server receives the cookie and processes it according to the data in it.
By using cookies, the website can transfer data between the client and the server, maintain state, and realize personalized user experience and other functions. **


Now start the detailed ideas and code display:

1. If you use cookies directly in the project, the writing method will be a bit complicated. At this time, we will talk about js-cookie, a Javascript library for operating cookies in the browser. It provides a set of simple and powerful APIs, conveniently set, read and delete cookies

Install js-cookie

npm install --save js-cookie


insert image description here
Create a new auth.js auth.js under the utils folder

import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

export function getToken() {
   
    
    
  return Cookies.get(TokenKey)//获取键名为Admin-Token的值
}

export function setToken(token) {
   
    
    
  return Cookies.set(TokenKey, token)//设置键名Admin-Token,值为token
}

export function removeToken() {
   
    
    
  return Cookies.remove(TokenKey)//移除键名为Admin-Token的值
}

2. Call login, get user information and exit interface in pinia. The main reason for putting the login interface, user information interface and logout interface in pinia is to facilitate state management and data sharing in the application

Login interface: When the user enters the user name and password to log in through the login interface, the login interface is responsible for sending a request to the server to verify the user's identity. Putting the login interface in Vuex can store the user's login status and authentication information, and call and update where needed. This way, other components can easily access and use user login information.
Get user information interface: In the application, there may be multiple components that need to get the user's personal information to display or perform certain operations. By placing the interface for obtaining user information in Vuex, unified management and sharing of data can be realized. When the user logs in, the user information is saved in Vuex, and other components can directly obtain user information from Vuex without separately requesting data in each component. Logout
interface: the logout interface is responsible for clearing the user's login status, and will The user is redirected to the login page. Putting the logout interface in Vuex can easily update the login status and clear user information, ensuring that other parts of the application can respond in a timely manner.

By putting these interfaces in Vuex, it is convenient to perform state management and share data, and improve the maintainability and scalability of the code. At the same time, storing data centrally in Vuex also helps to avoid frequent data transfer between components and improves the performance of the application.

Create a new index.js and a new modules folder under the store folder, create a new user.js and index.js and
create a pinia instance object in index.js, and export it to the outside
. The details are as follows:

import {
   
    
     createPinia } from "pinia"
const store = createPinia()
export default store

user.js
insert image description here

First introduce defineStore, pinia defines store through defineStore

import {
   
    
    defineStore} from "pinia"

Introduce the interface for logging out, obtaining user information and logging in

import {
   
    
     login, logout, getInfo } from '@/api/login'

Then introduce the method of operating token

import {
   
    
     getToken, setToken, removeToken } from '@/utils/auth'

details as follows:

import {
   
    
    defineStore} from "pinia"
import {
   
    
     login, logout, getInfo } from '@/api/login'
import {
   
    
     getToken, setToken, removeToken } from '@/utils/auth'

//对 `defineStore

Guess you like

Origin blog.csdn.net/weixin_49668076/article/details/131944091