Webpack, Vue, Vuex, VUe-Router, Axios,less, VUe-CLI, element-UI,iVue……. Initialize the project using vue-CLI. Vue init webpack init webpack 1. Set the IP address of the interface on the local server

 proxyTable: {
      '/': {target:'http://localhost:8080'.changeOrigin:true.pathRewrite: {'/':'/'}}},Copy the code

2. Encapsulate AXIos request and send JSON data and intercept request and response processing

Json.stringfy = json.stringfy = json.stringfy = json.stringfy = json.stringfy = json.stringfy This code combines the message and loading of element-UI

/** * Created by visupervi on 2018-07-14. */
import axios from 'axios'
import qs from 'qs'
import {Message,Loading } from 'element-ui'
import router from '.. /router'
axios.defaults.withCredentials = true;
let loadingInstance;
const opts = {
  lock: true.text: 'Loading'.background: 'rgba (255, 255, 255, 0.3)'.customClass: 'Please be patient'
}
const Axios = axios.create({
  baseUrl:' '.// Check your address
  timeout:3000.responseType:'json'.withCredentials:true.headers: {"Content-type":"application/json; charset=utf-8"//x-www-form-urlencoded}}); Axios.interceptors.request.use(config= >{

  if(
    config.method == 'post' ||
    config.method == 'put' ||
    config.method == 'delete' ||
    config.method == 'axios'
  ){
    loadingInstance = Loading.service(opts);
    if(config.method == "put"){ config.data = qs.stringify(config.data); }}if(localStorage.token){
    config.headers.Authorization = localStorage.token;
    // console.log(config.headers.Authorization);
    // loadingInstance = Loading.service(opts);
  }
  return config;
},error =>{
  Message({
    showClose:true.message:error,
    type:'error.data.error.message'
  });
  return Promise.reject(error.data.error.message)
});

Axios.interceptors.response.use(
  res= > {
    setTimeout(function () {
      loadingInstance && loadingInstance.close();
    }, 2000);
    if(res.data && res.data.success){
      Message({
        showClose:true.message:res.data.error.message.message
        ? res.data.error.message.message
          : res.data.error.message,
        type:'error'
      });
      return Promise.reject(res.data.error.message);
    }
    // loadingInstance.close();
    return res;
  },
  error => {
    if (!window.localStorage.getItem("userInfo")) {
      router.push({
        path: "/"
      });
    } else {
      let lifeTime =
        JSON.parse(window.localStorage.getItem("userInfo")).lifeTime *
        1000;
      let nowTime = new Date().getTime(); // Timestamp of the current time
      if (nowTime > lifeTime) {
        Message({
          showClose: true.message: "Login status information expired, please log in again.".type: "error"
        });
        router.push({
          path: "/"
        });
      } else {
        if (error.response.status === 403) {
          router.push({
            path: "/error/403"
          });
        }
        if (error.response.status === 500) {
          router.push({
            path: "/error/500"
          });
        }
        if (error.response.status === 502) {
          router.push({
            path: "/error/502"
          });
        }
        if (error.response.status === 404) {
          router.push({
            path: "/error/404"}); }}}// let errorInfo = error.data.error ? error.data.error.message : error.data;
    let errorInfo = error.data && error.data.error && error.data.error.message || error.data;
    return Promise.reject(errorInfo); });export default {

  // As a plug-in, you can use the vue. use method directly
  install: function(Vue, Option) {
    Object.defineProperty(Vue.prototype, "$http", { value: Axios }); }};Copy the code

3. Reference the vuEX storage login status


/** * Created by visupervi on 2018-07-17. */
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const token = JSON.parse(localStorage.getItem('token') | |null);

const store = new Vuex.Store({
  state(){
    return {
      userInfo: {token: token,
        userName:"".lifeTime:null}}},mutations:{
    setToken(state,token,name){
      state.userInfo.token = token;
      state.userInfo.lifeTime = (new Date()).getTime();
      state.userInfo.userName = name;
      localStorage.setItem('userInfo'.JSON.stringify(state.userInfo));
    },
    delToken(state){
      state.token = null;
      localStorage.removeItem('userInfo'); }},getters:{
    getToken(){
      if(! localStorage.getItem("userInfo")){
        localStorage.setItem("userInfo"}, {})return localStorage.getItem("userInfo"); }}});export default store;

Copy the code

The mutation is described in the official website, including how to use the function. Commit to trigger

4. Route request processing

A meta was added to the route to specify whether login permissions are required

const router = new Router({
  routes: [{path: '/'.name: 'userLogin'.component: userLogin,
      meta: {
        requireLogin: false}, {},path:'/listVue'.name:'listVue'.component:listVue,
      meta: {
        requireLogin: true}}}]); router.beforeEach((to, from, next) = > {
  if (to.matched.some(res= > res.meta.requireLogin)) {
    // Determine whether the login permission is required
    // console.log(this.$store.getters.getToken);
    let userInfo = window.localStorage.getItem("userInfo");
    // console.log(JSON.parse(userInfo).lifeTime);
    if(userInfo! =null) {
      // Determine whether to log in
      let lifeTime =
        JSON.parse(userInfo).lifeTime * 1000;
      // console.log(lifeTime)
      let nowTime = (new Date()).getTime(); // Timestamp of the current time
      console.log(nowTime);
      if (nowTime < lifeTime) {
        next();
      } else {
        Message({
          showClose: true.message: "Login status information expired, please log in again.".type: "error"
        });
        next({
          path: "/"}); }}else {
      // If no login is displayed, the login page is displayed
      next({
        path: "/"}); }}else{ next(); }});export default router;

Copy the code

From here, projects can run separately and can request and jump