“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

There must be a user login form in the project, so we need to encapsulate judgment login status, to satisfy the project application, of course, just do not use the packaging, will cause the high coupling, code redundancy, etc. As a result, the project may be often used in vuex state management to the state of the login, that if the project is to use less than state management, You can then use simple encapsulation to determine login status.

Login state encapsulation

If we want to generally encapsulate the login state, we need two functions, namely getToken to obtain the stored token and isLogin to determine whether to log in using the token. We need to create a new folder in the SRC directory, or create a new auth.js file directory in which we encapsulate the request.

getToken

To obtain the token, use localStorage to obtain the token and return the value to the function

export function getToken() {
  return localStorage.getItem("token");
}
Copy the code

isLogin

To determine login, you only need to call getToken to obtain the token value and return the Boolean value to determine whether the user is logged in

export function isLogin() {
  if (getToken()) {
    return true;
  }
  return false;
}
Copy the code

In addition, there are other places to use getToken in the project, such as the value of the token to be transferred in the request header

Method of use

We’ll just import it as needed in the page we want to use, for example, we’ll just import isLogin

import { isLogin } from "@/request/auth";
Copy the code

So after the introduction, somebody said, do we decide if else, nonono is low, hidden score is low, let’s see what I’m going to do

Mounted () {// isLogin()? Console. log("isLogin") : (console.log("Need to login"), this.$message.error(' not logged in '), this. },Copy the code

In Mounted mode, the login status is determined in the hook after the page initialization. In Mounted mode, the login status is determined in the hook after the page initialization. In Mounted mode, the login status is determined in the hook after the page initialization.

Other than that, what do I write here? If (element) {if (element) {if (element) {if (element) {if (element) {

setToken

Since getToken is encapsulated, setToken must be encapsulated again for convenience

export function setToken(token) {
  return localStorage.setItem("token", token);
}
Copy the code

The last

Here is a sophomore front primary school students some of the project summary, I hope to bring you help, if it is helpful to you, point a small praise praise go 🥳