1. Change the address of dev.env.js BASE_API in config folder to the public part of the request backend

BASE_API: '" http://192.168.xx.xx".Copy the code

Vue (login.vue,regist.vue) in views and set path in index.js of router

login.vue

<template>
  <div class="login-container">
        <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left"
                 label-width="0px"
                 class="card-box login-form">
          <h3 class="title"</h3> <el-form-item prop="name">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user"/>
        </span>
              <el-input name="name" disabled type="text" v-model="loginForm.name" autoComplete="on"
                        placeholder="Username"/>
            </el-form-item>
            <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"></svg-icon>
        </span>
              <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password"
                        autoComplete="on"
                        placeholder="Password"></el-input>
              <span class="show-pwd" @click="showPwd"><svg-icon icon-class="eye"/></span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin"> login < / el - button > < / el - form - item > < / el - form > < / div > < / template > < script >export default {
    name: 'login'.data() {
      const validateUsername = (rule, value, callback) => {
        if (value.trim().length<1) {
          callback(new Error('User name cannot be empty'))}else {
          callback()
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.trim().length < 1) {
          callback(new Error('Password cannot be empty'))}else {
          callback()
        }
      };
      return {
        loginForm: {
          name: ' ',
          password: ' '
        },
        loginRules: {
          name: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePass}]
        },
        loading: false.pwdType: 'password'
      }
    },
    methods: {
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ' '
        } else {
          this.pwdType = 'password'}},handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store.dispatch('Login', this.loginForm).then(() => {
              this.loading = false;
              this.$router.push({path: '/'});
            }).catch((e) => {
              this.loading = false})}else {
            console.log('error submit!! ')
            return false
          }
        })
      }
    }
   }
</script>
Copy the code

router/index.js

{ path: '/login', component: _import('Login/login'), hidden: true }
Copy the code

3. Write the interface address for docking with the back end in login.js in API, define user in user.js in modules in stores, and write state, mutations, action, and the specific request operation in action. Login. vue or regist.vue calls the request written in user.js and getters that define the store in getter.js

api/login.js

import request from '@/utils/request'
export function login(name,password) {
  return request({
    url: '/XX/XX',
    method: 'post',
    data: {
      name,
      password
    } 
  })
}
Copy the code

stores/modules/user.js

   import { login,regist,logout } from '@/api/login'
   import { getToken,setToken } from '@/utils/auth'

   const user = {
     state: {
       name:' ',
       token:' '
     },

     mutations: {
       SET_NAME: (state, name) => {
         state.name = name;
       },
       SET_TOKEN: (state, token) => {
         state.token = token;
         setToken(token); }}, actions: {// Login({commit}, userInfo) {const name = userinfo.name.trim (); const password = userInfo.password.trim();return new Promise((resolve, reject) => {
           login(name, password).then(response => {
             const data = response.data;
             commit('SET_NAME', data.name);
             commit('SET_TOKEN', data.token);
             setName(data.name);
             setToken(data.token); resolve(response); }). Catch (error => {reject(error)})})}, // Register Regist({commit}, userInfo) {const name= userinfo.name.trim (); const password = userInfo.password.trim();return new Promise((resolve, reject) => { 
           regist(name, password).then(response => { 
             const data = response.data; 
             commit('SET_NAME', data.name); 
             commit('SET_TOKEN', data.token);
             setName(data.name);setToken(data.token); resolve(response); }). The catch (error = > {reject (error)})})}, / / LogOut LogOut ({commit, state} {return new Promise((resolve, reject) => {
         logout().then(response => {
           commit('SET_NAME'.' ');
           commit('SET_TOKEN'.' ');
           setName(' ');
           setToken(false); //removeName(); //removeToken(); resolve(response); }). Catch (error => {reject(error)})})}, // Front-end logout FedLogOut({commit}) {return new Promise(resolve => {
     setToken(false);
 commit('SET_TOKEN'.false);
 resolve()
         })
       }
     }
   }
   export default user
Copy the code

getter.js:

const getters={
 name:state=>state.user.name,
 token:state=>state.user.token
}
export default getter
Copy the code

4. Operate cookies in auth.js in utils, such as writing, reading, deleting user permissions, whether to sign in, etc

import Cookies from 'js-cookies'
export function setName(name) {
 return Cookies.set("name", name);
}
export function getName() {
 return Cookies.get("name");
}
export function setToken(token) {
 return Cookies.set("token", token);
}
export function getToken() {
 return Cookies.get("token");
}
Copy the code

5. Write a whitelist in permission.js, block jumps that are not in the whitelist and then jump to login, and check whether the user has permission to log in, etc

import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress Progress bar style import {Message} from'element-ui'
import {getName, getToken} from "@/utils/auth"; // const whiteList = ['/login'.'/regist']; BeforeEach ((to, from, next) => {nprogress.start ();if(whiteList.indexOf(to.path) ! == -1) { next(); }else {
    if (getToken()==="true") {
      next();
      NProgress.done()
    } else {
      next({path: '/login'}); Router. AfterEach (() => {nprogress.done () // End Progress})Copy the code

6. Write interception codes in request.js in utils, intercept specific codes returned by the back end and do the corresponding operations

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '.. /store'// Create an axios instance const service = axios.create({baseURL: process.env.base_api, // API base_URL timeout: 15000 // request timeout); / / respone interceptor service. Interceptors. Response. Use (response = > {/ * * * code for the 200 is thrown fault can be modified with his business * / const res = response.data; //const res = response;if(res.code ! = ='200'&& res.code ! = = 200) {if (res.code === '4001' || res.code === 4001) {
        MessageBox.confirm('Wrong username or password, please log in again'.'Log in again', {
          confirmButtonText: 'Log in again',
          cancelButtonText: 'cancel'.type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {location.reload()// To re-instantiate the VUe-router object to avoid bugs})})}if (res.code === '4009' || res.code === 4009) {
        MessageBox.confirm('This username already exists, please register again! '.'Re-register', {
          confirmButtonText: 'Re-register',
          cancelButtonText: 'cancel'.type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {location.reload()// To re-instantiate the VUe-router object to avoid bugs})})}return Promise.reject('error')}else {
      return response.data
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
)
 
export default service
Copy the code