Project Course Design
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-P6n6pPpI-1639934454800)(assets/image-20200810012833240.png)]
Setting up environment for human resources
Understanding and introduction of vue-element-admin
Goal: Learn and understand the common Vue background integration scheme**vue-element-admin**
vue-element-admin Is a back-end front-end solution based on vue and element-ui Realization. It uses the latest front-end technology stack, built-in i18 internationalization solutions, dynamic routing, privilege validation, extracts a typical business model, provides rich functional components, which can help you quickly build enterprise-level mid-background product prototypes.
vue-element-admin It is a background integration solution that integrates many business scenarios and functions of PC projects, especially in the current SPA trend, from which we can get many mature solutions.
vue-element-admin Have a mature Integration scheme , which contains all the business functions and scenarios, is not suitable for secondary development, but can be learned and used through a case in the project.
Here is Official address
Here is Online demo address
If you want to see the specific functions and effects of this project, you can pull the code and start a preview
$ git clone https://github.com/PanJiaChen/vue-element-admin.git #pull code $ cd vue-element-admin #Switch to specific directory $ npm run dev #Start development debugging mode to view the package. The scripts in the JSON file know the startup command
Note: If the current project download speed is too slow, you can download the compressed package of code directly to run
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-sygqAUK-1639934454801) (assets/image-2020070319390.png)]
The integration scheme is not suitable for us to use directly for secondary development. Base Template Is a better choice
The basic template, which contains some basic function templates for the basic login/authentication/home page layout on which we can extend functionality and redevelop projects directly
Tasks in this section: Browse the documentation for vue-element-admin to learn about this integration scenario
Some basic preparations before building the project
Goal: Describe the environment and tools required to build a vue platform project
The next step is a large project, we need better environmental preparation and resources in front, so check our environment and resources in advance
nodejs environment
Noejs is an essential environment for current front-end engineering development, using the **npm** functionality of nodejs to manage dependent packages
View versions of node and npm
$ node -v #View node version $ npm -v #View npm version
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-YiLyOcuz-1639934454801) (assets/image-202007061303160.png)]
git version control
The git version control tool is currently the most popular distributed version management tool, code ** submission, check-out, log **, all need to be done through Git
View git installation version
$ git --version #View git installation version
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-VFJMu9yg-1639934454802)(assets/image-20200706131337563.png)]
npm Taobao mirror
npm is a very important npm management tool. Since npm servers are located abroad, it is generally recommended to set npm as a mirror of Taobao in China.
Set Taobao Mirror
$ npm config set registry https://registry.npm.taobao.org/ #Set Taobao mirror address $ npm config get registry #View mirror address
vscode editor
The vscode editor is a powerful coding tool and rich plug-in system for front-end development. It is very suitable for front-end projects.
vscode Editor Plugin + vetur + eslint
vetur is a plug-in support based on single file components, eslint is a plug-in tool based on code validation
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-JmuGYaZQ-1639934454802)(assets/image-20200706134607517.png)]
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-E2Txrd8L-1639934454802) (assets/image-2020070614330.png)]
In addition, eslint needs to configure some parameters in vscode
{ "eslint.enable": true, "eslint.run": "onType", "eslint.options": { "extensions": [ ".js", ".vue", ".jsx", ".tsx" ] }, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } }
Technical stack of this project Technical stack of this project is based on ES2015+,vue,vuex,vue-router ,vue-cli ,axios and element-ui
Task of this section: Everyone should check their development environment and resources, especially the npm Taobao mirror needs extra attention
Project Template Launch and Directory Introduction
Goal: Pull out the project's basic template and introduce the catalog
Is the basic template for vue-element-admin the same as the project we developed earlier? In this section, we describe the project catalogue
git pull base project template
$ git clone https://Github. Com/PanJiaChen/vue-admin-template. Git hrsaas #Pull base template to hrsaas directory
Install project dependencies (located under project directory)
$ npm install #Installation Dependency
Start Project
$ npm run dev #Start Services in Development Mode
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-KIqi8g1n-1639934454802)(assets/image-20200708010741325.png)]
When the project is finished, the browser automatically opens the login page for the underlying template, as illustrated above
directory structure
This project has already generated a basic development framework for you, providing various functions and pits covering mid-background development. Below is the catalog structure of the entire project.
├── build # Build correlation ├── mock # Project mock simulation data ├── public # Static Resources │ │── favicon.ico # favicon Icon │ └── index.html # html template ├── src # source code │ ├── api # All Requests │ ├── assets # Static resources such as theme fonts │ ├── components # Global Common Components │ ├── icons # Project All svg icons │ ├── layout # Global layout │ ├── router # Route │ ├── store # Global store management │ ├── styles # Global Style │ ├── utils # Global Common Method │ ├── vendor # Public vendor │ ├── views # views All Pages │ ├── App.vue # Entry Page │ ├── main.js # Initialization of entry file load components, etc. │ └── permission.js # Rights Management │ └── settings.js # configuration file ├── tests # test ├── .env.xxx # Environment variable configuration ├── .eslintrc.js # eslint configuration item ├── .babelrc # babel-loader configuration ├── .travis.yml # Automated CI Configuration ├── vue.config.js # vue-cli configuration ├── postcss.config.js # postcss configuration └── package.json # package.json
At this point, you may be dazzled because there are too many files in the generated directory. The most important thing we pay attention to when working on a project is the **src** directory, which contains all the source code and resources. As for other directories, it is the configuration of the project's environment and tools.
Tasks in this section: Follow the steps of operation and explanation, pull code, install dependencies, run projects, read directories and files
This section takes note of whether your npm has a Taobao mirror set up
Project Running Mechanism and Code Comments
Goal: Understand the basic mechanisms and infrastructure of the current template
How does dazzling directories and files really work? Let's do some basic explanations to help you understand and develop better.
├── src # source code │ ├── api # All Requests │ ├── assets # Static resources such as theme fonts │ ├── components # Global Common Components │ ├── icons # Project All svg icons │ ├── layout # Global layout │ ├── router # Route │ ├── store # Global store management │ ├── styles # Global Style │ ├── utils # Global Common Method │ ├── vendor # Public vendor │ ├── views # views All Pages │ ├── App.vue # Entry Page │ ├── main.js # Initialization of entry file load components, etc. │ └── permission.js # Rights Management │ └── settings.js # configuration file
main.js
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-p6MyhUl8-1639934454803)(assets/image-20200824153141764.png)]
Please comment out the part of **mock data, delete the mock** folder under src, we can develop without simulation data, as shown in the figure
Also, please comment out **vue. Config. before: require('. /mock/mock-server.js') in js**
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-36L8eJX4-1639934454803)(assets/image-20200811013813693.png)]
App.vue
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-r7NdT1SX-1639934454803)(assets/image-20200824155103340.png)]
permission.js
Under src, except main.js has two more files, permission.js and **settings.js**
permission.js is a file that controls page login permissions. It's hard to understand the code here without going through the build process, so comment on the code here and build from 0 to 1 when we build the permission function.
commented code
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-oRx6lDP9-1639934454803)(assets/image-20200708014558617.png)]
settings.js is the configuration for some project information, which has three properties Title (project name), fixedHeader (fixed header), sidebarLogo (display left menu logo)
**settings. The file in js** is referenced elsewhere, so no changes will be made to it here for now
Vuex structure
The current Vuex architecture uses modules to manage the shared state, which are as follows
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-54kkAbV8-1639934454803)(assets/image-20200824165153331.png)]
Where app.js module and settings.js module, the function is complete, there is no need to modify. user.js module is what we need to focus on later, so here we will use user. Contents inside JS are deleted and a default configuration is exported
export default { namespaced: true, state: {}, mutations: {}, actions: {} }
Also, because the state in user is referenced in getters, we change the state in getters to
const getters = { sidebar: state => state.app.sidebar, device: state => state.app.device } export default getters
scss
The project also uses scss As an extended language of css, under the **styles** directory, we can find the relevant files of scss, related usage Next Measure Explanation [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-CUx6uc4s-1639934454803) (assets/image-202008241727384.png)]
icons
The icons are structured as follows
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-CFBEb4ID-1639934454804)(assets/image-20200824173239955.png)]
The above is the basis and introduction of vue-element-admin, I hope you will experience a basic operating mechanism of templates in this process
Tasks in this section: You will learn more about the above according to the catalog structure and design drawings
Understanding and use of SCSS processing
Objective: To understand and learn the specifications and usage of Scss processors
First of all, what is the relationship between sass here and our scss
sass and SCSS are actually ** the same ** css preprocessing language. SCSS is a new syntax introduced by Sass 3 with suffix names of **. sass and. There are two types of scss.
The suffix name before sass version 3.0 is. sass, the suffix name after version 3.0. scss.
The two are different. The writing specification of scss after sass is basically the same as css. In the sass era, there are strict indentation specifications and there are no'{}'and';'.
The scss rule is consistent with the css specification.
Set up a small test environment
To make scss easy to use, we can install a plug-in named **easy sass** in vscode, but we only apply the plug-in in the workspace of the project, because there is no need for the plug-in to assist in the project
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-wemnyRNj-1639934454804)(assets/image-20200825143713888.png)]
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-2u0AwhwU-1639934454804)(assets/image-20200825143800666.png)]
First we create a new folder, test, and then we create a new index under test. HTML and create a new test.scss
The page structure is as follows
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./test.css"> </head> <body> <nav> Scss style </nav> <div id="app"> Hello World </div> <div id="content"> <article> <h1>Article Title</h1> <p>Article Content <a href="">Baidu</a> </p> </article> <aside> sidebar </aside> </div> </body> </html>
The **easy sass plug-in we use automatically helps us test. SCSS => test. Css**
variable
sass uses the $symbol to identify variables
$highlight-color: #f90
Above we declared a variable named **$highlight-color**, which we can use anywhere
#app { background-color: $highlight-color; }
Multiple attribute values separated by spaces can also identify variables
$basic-border: 1px solid black;
#app { background-color: $highlight-color; border: $basic-border }
Range of variables
Unlike CSS attributes, variables can exist outside the definition of a CSS rule block. When a variable is defined within a CSS rule block, it can only be used within that rule block. If they appear in any form of {...} In blocks (such as @media or @font-face blocks), the same is true:
$nav-color: #F90; nav { $width: 100px; width: $width; color: $nav-color; background-color: black } # After compilation nav { width: 100px; color: #F90; background-color: black; }
In this code, $nav-color is defined outside the rule block, so it can be referenced in this stylesheet like a NAV rule block. $ The variable width is defined within the NAV {} rule block, so it can only be used within the NAV rule block. This means that you can define and use the $width variable elsewhere in the stylesheet without affecting it here.
Nested Grammar
Like less, scss also supports the syntax of ** nested **
#content { article { h1 { color: #1dc08a } p { font-style: italic; } } aside { background-color: #f90 } }
After transformation
#content article h1 { color: #1dc08a; } #content article p { font-style: italic; } #content aside { background-color: #f90; }
&Parent Selector
If you want to set a specific child element
such as
#content { article { h1 { color: #1dc08a } p { font-style: italic; } a { color: blue; &:hover { color: red } } } aside { background-color: #f90 } }
Learn here that scss and less have many similarities. The biggest difference is how variables are declared. Less uses the **@ variable name, while scss uses the $variable name**
Now let's look at styles/variables in the template. SCSS
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-EesjMsjH-1639934454805)(assets/image-20201017230542301.png)]
The above file, in fact, defines some of our basic values, which make it easy for everyone to process in a file uniformly.
Tasks in this section: Understanding and mastering scss
Set up a remote Git repository and complete the initial submission
Target at Code cloud perhaps github Set up the corresponding remote warehouse on and submit the code branch
Set up a remote warehouse
Remote warehouse establishment only requires direct operation on the website
Local Project Submission
Note: Since our previous project was cloned directly from vue-element-admin **, it has the original submission record, so to avoid conflicts, first clone the original. git** Folder Deleted
And git initialization of the project
$ git init #Initialize project
$ git add . #Add changes to staging $ git commit -m 'Human Resources Project Initialization' #Refer temporary storage to local warehouse
View Version Log
$ git log #View Version Log
Push to remote warehouse
Pushing to a remote warehouse generally starts with **Remote warehouse address** Replace with local warehouse alias
$ git remote add origin <Remote warehouse address> #Add Remote Warehouse Address
When we don't know the origin address of our warehouse, we can view the current remote warehouse address by command
$ git remote -v #View Remote Warehouse Address Mapping for Local Warehouse
Push master branch to remote warehouse
$ git push -u origin master #Push master branch to remote warehouse address represented by origin
Tasks for this section: Students submit the pulled-down items to their warehouses based on the above actions
Introduction of API module and request encapsulation module
Target Describes separate requests for API modules and encapsulation of request modules
Introducing the interceptor for Axios
The project was developed using a separate module encapsulation of the API and an axios interceptor
The axios interceptor works as follows
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-btBXc8ru-1639934454805)(assets/image-20200811012945409.png)]
axios interceptor
axios is a third-party tool for network requests to intercept requests and responses
create a new axios instance
// A new axios instance was created const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 5000 // timeout })
request interceptor
Request Interceptor handles token's ** Unified Injection problem **
// Request Interceptor for axios service.interceptors.request.use( config => { // do something before request is sent if (store.getters.token) { // let each request carry token // ['X-Token'] is a custom headers key // please modify it according to the actual situation config.headers['X-Token'] = getToken() } return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } )
Response Interceptor
Response Interceptor mainly handles the returned ** data exceptions ** and ** data structure ** issues
// 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 !== 20000) { Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 }) 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) } )
In order to write the code more clearly, we will comment out the original code and replace it with the following code
// Export an instance of axios with request interceptor response interceptor import axios from 'axios' const service = axios.create() // Create an instance of axios service.interceptors.request.use() // request interceptor service.interceptors.response.use() // Response Interceptor export default service // Export axios instance
Separate encapsulation of api modules
We habitually place all network requests under the api directory for unified management, divided by modules
Separate encapsulation code
import request from '@/utils/request' export function login(data) { return request({ url: '/vue-admin-template/user/login', method: 'post', data }) } export function getInfo(token) { return request({ url: '/vue-admin-template/user/info', method: 'get', params: { token } }) } export function logout() { return request({ url: '/vue-admin-template/user/logout', method: 'post' }) }
In the code above, an encapsulated request tool is used, and requests from each interface are exported individually** using a method. The advantage of this is that we can directly reference our exported request method wherever we need it
For better future development, we can start with user.js code method set to empty, subsequent corrections
// import request from '@/utils/request' export function login(data) { } export function getInfo(token) { } export function logout() { }
Submit Code
Tasks in this section: Clean up the code for requests and user modules, understand requests and module encapsulation
Public Resource Pictures and Uniform Styles
Target Puts some common picture and style resources into the specified directory
Now that we have briefly introduced the basic modules as a whole, we need to unify the pictures and styles used in this project.
Picture Resources
Picture resources In the picture file of the course materials, we just need to place a copy of the **common** folder in the **assets** directory
style
Style resources are in the Resource/Style directory
Modify **variables.scss**
Add**common.scss**
We are in ** variables.scss** added some basic variable values
We provide a public ** common.scss** Styles, which are built-in to help us quickly implement page styles and layouts during development
Place both files in the styles directory and **index. Introduce this style in scss**
@import './common.scss'; //Introduce common.scss stylesheet
Submit Code
Note in this section: Note that in scss files, other style files are introduced through **@import**, and you need to be careful to add a semicolon at the end, otherwise errors will occur
This section of the task places pictures and styles of public resources in designated locations