Vue front-end template framework --vue-admin-template

1. Introduction

vue-admin-template is a set of background management system basic templates (minimum simplified version) based on vue-element-admin, which can be used as templates for secondary development.

GitHub address:GitHub - PanJiaChen/vue-admin-template: a vue2.0 minimal admin template

Suggestion: You can carry out secondary development on the basis vue-admin-templateof , vue-element-adminuse it as a toolbox, and copy any functions or components you want from vue-element-adminthere .

Two, use

Modify the project name vue-admin-template to "your own defined project name" and
decompress the compressed package
. Enter the directory
cd "under your own project name"
and install it depends on
npm install
to start. After execution, the browser will automatically pop up and visit http://localhost:9528/
npm run dev

3. Source code directory structure

|-dist Packaged project generated by production environment
|-mock Generate simulation data
|-public contains folders that will be automatically packaged into the root path of the project
    |-index.html the only page
|-src
    |-api contains interface request function modules
        |-table.js table list mock data interface request function
        |-user.js user login related mock data interface request function
    |-assets public resources that need to be used in components
        |-404_images 404 page images
    |-components non-routing components
        |-SvgIcon svg icon component
        |-Breadcrumb breadcrumb component (level component in the horizontal direction of the head)
        |-Hamburger is used to click to switch the icon component of the left menu navigation
    |-icons
        |-svg contains some svg image files
        |-index. js Globally registers the SvgIcon component, loads all svg images and exposes an array of all svg file names
    |-layout
        |-components Some subcomponents that make up the overall layout
        |-mixin component Reusable code
        |-index.vue The overall background management Interface Layout Components
    |-router
        |-index.js router
    |-store
        |-modules
            |-app.js management application related data
            |-settings.js management setting related data
            |-user.js management background login user related data
        |-getters.js provided Getters calculation properties of sub-module related data
        |-index.js store of vuex
    |-styles
        |-xxx.scss some styles that project components need to use (using scss)
    |-utils some utility functions
        |-auth.js operation login user token cookie
        |-get-page-title.js Get the title of the webpage to be displayed
        |-request.js Axios secondary package module
        |-validate.js inspection related tool functions
        |-index.js date and request parameter processing related tool functions
    |-views routing component folder
        |-dashboard home page
        |-login login
    |-App.vue application root component
    |-main.js entry js
    |-permission.js is a module that uses global guards to implement routing permission control
    |-settings.js is a module that contains application setting information
|-.env.development specifies the proxy server prefix path for the development environment
|-. env.production specifies the proxy server prefix path for the production environment
|-.eslintignore eslint ignore configuration
|-.eslintrc.js eslint check configuration
|-.gitignore git ignore configuration
|-.npmrc specifies npm Taobao mirror and sass Download address
|-babel.config.js babel configuration
|-jsconfig.json for configuration of vscode import path prompts
|-package.json current project package information
|-package-lock.json The accuracy of the third-party packages that the current project depends on Information
|-vue.config.js webpack related configuration (such as: proxy server)

4. Modify the login function

Because the template uses mock data and is not connected to the backend system.

So when we want to connect to the backend system we wrote, we need to modify vue-admin-template.

 1. Because the browser has restrictions on Ajax requests, the following three places are different, and cross-domain problems will occur.

Causes of cross-domain problems: access protocol, address IP, port number

Front-end address: http://localhost:9258

Backend address: http://localhost:8800

Solution:

the first method:

Inside the .env.development file, put

                VUE_APP_BASE_API = '/dev-api'
modified VUE_APP_BASE_API = 'http://localhost:8800'

 

The second method:

Inside the vue.config.js file

        Comment out the mock interface configuration

        Configure the proxy to forward requests to the target interface

// before: require('./mock/mock-server.js') 
proxy: { 
  '/dev-api': { // Match all request paths starting with '/dev-api' 
    target: 'http:/ /localhost:8800', 
    changeOrigin: true, // support cross-domain 
    pathRewrite: { // rewrite path: remove '/dev-api' at the beginning of the path 
      '^/dev-api': '' 
    } 
  } 
}

2. Modify the request status code of src/utils/request.js

Since the front-end accesses the back-end data, it will pass a status code. The status code returned by the back-end may be 200, but the front-end default is 20000. At this time, you need to change the two to the same, and modify the judgment of the front-end status code by default. conditions.

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

3. Modify the front-end interface path

Change the url address in src/api/user.js to the sending address of your own backend.

import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/admin/system/index/login',
    method: 'post',
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/admin/system/index/info',
    method: 'get',
    params: { token }
  })
}

export function logout() {
  return request({
    url: '/admin/system/index/logout',
    method: 'post'
  })
}

4. Modify the login request of the backend

@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    //login
    //{"code":20000,"data":{"token":"admin-token"}}
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        Map<String, Object> map = new HashMap<>();
        map.put("token ", "admin-token-a");
        return Result.ok(map);
    }

    //info
//    {"code":20000,"data":{"roles":["admin"],
//        "introduction":"I am a super administrator",
//                "avatar":"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
//                "name":"Super Admin"}}
    @GetMapping("/info")
    public Result info(HttpServletRequest request) { 
        Map<String, Object> map = new HashMap<>();
        map.put("roles", "[admin]");
        map.put("introduction", "管理员");
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name", "Super Admin");
        return Result.ok(map);
    }
}

5. Add interface for login failure

vue edge:

// user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
export function logout() {
  return request({
    url: '/admin/system/index/logout',
    method: 'post'
  })
}

Backend interface:

 @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

Another way to log out is:

Modify the logout to exit directly without sending a request.

// user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
 
    })

5. Help

If you feel that it is helpful to you, please give me a little attention, which is an enduring motivation.

Guess you like

Origin blog.csdn.net/m0_57037182/article/details/127684812