Note source: Hook Education – big front end employment Training camp
Content: Notes, thoughts and experiences in the process of learning
Build the Vue project
- View the VUE version:
Vue -V
- Create a project structure:
vue create lagou-backstage-cwn
- Select project use Configuration, here select Custom configuration
- Select the plug-in you want to use
- ◉
Choose Vue veron
– Select later manually select Vue version (default 2.XX, we also temporarily use 2.XX) - ◉
Babe
L-babel function - ◉
Router
– vueRouter routing - ◉ `
- ◉
CSS Pre-processors
– CSS is precompiled - ◉
Linter / Formatter
– Code style management tool
- ◉
- To ask which version of VUE you want to use, select 2.x
- Ask whether the router uses history mode, but does not, type n and press Enter
- Asks for the CSS compiler type, temporarily selected here
Sass/SCSS (with dart-sass)
- Select the code validation style, for now
ESLint + Standard config
- Ask when to verify code style, select both (save time and Git commit time)
- Ask whether to store the configuration separately or to store it
package.json
, select the individual file here. Road post management - If you want to save the above configuration information, enter n
- When you press Enter to create the project, you may be prompted to ask whether you want to upload it or not. Olo v“““`q1a Q The project is created
- Go to the directory,
cd.......
- Run the preview
npm run sever
Add git version management
Note: The following steps are based on the fact that you already have Git installed. If you do not have git installed, you will have a problem installing it first
-
Open the **. Gitignore file and you can see that it has been configured to upload files ignoring the node_modules and /dist folders ** (step 12 above)
.DS_Store node_modules /dist ....... Copy the code
-
Run git status to check the status of the Git repository. On Branch Master, nothing to commit, working tree clean is displayed
-
Create a repository on Github or open Source China and get the repository address
-
Git remote add git remote add git remote add git remote add
-
Git push -u alias master: git push -u alias master: git push -u alias master: git push -u alias master: git push -u alias master: git push -u alias master: git push -u alias master: git push -u alias master: git push
Directory Structure description
- The root directory
- Node_modules – Dependency package directory, which contains the dependency packages of the project
- Public – static resource directory, which is copied directly into the package directory without webpack processing
- SRC – Resources directory
- Assets – A directory for storing pictures and other files that may be used during development
- Components – Public components directory, which houses all public components
- Router-routing module directory. The index.js directory contains functions related to routing modules
- Store-vuex functional directory, which will be explained later
- View – View stores the directory for routing related page components
- App.vue – Root component, equivalent to the root instance used earlier
- Main.js – Entry file. It introduces modules to create vUE instances
- .browserslistrc – The target browser range, which will be used later for some browser compatibility processing
- . Editorconfig – Configuration file for the editor
- .eslintrc.js – esLint rule configuration file, code style Settings
- The.gitignore – git plugin was created for us to ignore node_modules content
- Babel.config.js – About the Babel configuration file
- Package-lock. json – NPM file, which records related package information
- Package. json -npm file, which records related package information
- Readme. md – Information file that can write document information
Adjust the initial directory
Delete some initialization files and add and adjust directories as required
- Delete some automatically generated files in the SRC directory
- Delete the logo. PNG file in assets. It is not needed
- Delete components under components, we don’t need them
- Delete all components under view, we don’t need them
- Create a new directory under the SRC directory
- Create a Services directory – To store interface module functions
- Create a styles directory to store global styles
- Create a utils directory to store tool-related modules
- Modify the file
- Delete the components introduced by router-link in app.vue. These components have been removed, and all styles
- Delete the routes mapping rule in the index.js file in the router directory. Delete the Home component introduced at the top. The components have been deleted and are no longer used
Some PRECAUTIONS for the CLI
- Import is applicable to all imported modules in the CLI
- Imported plug-ins need to be used
Vue.use(Introduced plug-ins)
Register with VUE to use - The main js below
Import router from './router' and import store from './store'
The default directory is the index.js file
Code specification and code style
- (This project uses) JavaScript Standard Style (Standardjs.com) code specification, relatively common and popular
- GitHub – Airbnb /javascript: Javascript Style Guide code specification
Standard was installed when the project was created above
Using the.eslintrc.js file to land the specification and introduce it into the.eslintrc.js file of the Vue project, the program forces the specification to be used and reports an error if it is written against the specification
module.exports = {
root: true.env: {
node: true
},
// let the specification land
extends: [
Lint is an eslint plugin that checks the vUE code and can be viewed in the VUE -> Style Guide
'plugin:vue/essential'.// The code style verification tool we use
'@vue/standard'].parserOptions: {
parser: 'babel-eslint'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'}}Copy the code
Error handling problems occur
- View the error message to get the last word of the error message, for example
12:22 error Extra semicolon semi
You getsemi
- ESlint – Pluggable JavaScript linter-ESlint – Chinese
- Click the rule to view the error information corresponding to all rule codes. You can search for the error information
** Custom verification rules – **.eslintrc.js
If we want to change some rules, we need to customize the code verification rules. After changing the rules, we need to restart serve
All we have to do is.eslintrc.js
Of the filerules
To add the configuration
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.// Custom rule: semicolons are allowed
'semi': 'off'
}
Copy the code
You can view the specific methodConfiguring ESLint – ESLintYou of the Rules
Normally, using ESLint would require us to configure rules manually, but using Standard helped us quickly introduce rules that made things a lot easier
Element component library
Excellent third-party component library, very suitable for the development of background management system projects
Official website address:
- Based on Vue3.0: Element – Site Rapid Prototyping Tool (Giee.io)
- Based on vue2.0: Element – site rapid prototyping tool
** Install using **
The specific method of official documentation is very clear, you can view the official website – components
-
The project installs element-UI for development dependency: NPM I element-uI-s
-
Introduce elements and theme files in main.js under SRC (fully introduced for now, on demand described later)
-
Register Element as a VUE plug-in
//main.js./ / introduce element - the UI import ElementUI from 'element-ui' // Introduce the element-UI theme file import 'element-ui/lib/theme-chalk/index.css' // Register element-UI as a vue plug-in Vue.use(ElementUI) .................. Copy the code
-
Tests whether element is available
<! -- App. Vue file -- > < template > < div id = "App" > < h1 > retractor education < / h1 > < the router - view / > <! Try introducing an Element component <el-button> <el-button type="primary"> </el-button> <el-button type="primary" </el-button> <el-button type="info"> </el-button> <el-button type="warning"> < el - button type = "danger" > dangerous button < / el - button > < / el - row > < / div > < / template >...Copy the code
Style to deal with
The focus here is on setting global styles and modifying Settings for the Element theme
-
Create four new SCSS files under src-styles (using the SCSS precompiler here)
-
Index. scss-vue imports files, which can be regarded as entry files
// Add variables to the variables file to get all variables @import './variables.scss'; // Set the HTML style html { font-family: $font-family; -webkit-text-size-adjust: 100%; -webkit-tap-highlight-color: rgba(0.0.0.0); // better Font Rendering -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } // Set the body style body { margin: 0; background-color: $body-bg; } // Change the element theme color. $--color-primary: $primary-color; $--color-success: $success-color; $--color-warning: $warning-color; $--color-danger: $danger-color; $--color-info: $info-color; // Change the icon font path variable, required $--font-path: '~element-ui/lib/theme-chalk/fonts'; // Introduce the element default theme file (style file) @import '~element-ui/packages/theme-chalk/src/index'; // node_modules/element-ui/packages/theme-chalk/src/common/var.scss // overrides // .el-menu-item, .el-submenu__title { // height: 50px; // line-height: 50px; // } .el-pagination { color: #868e96; } // components .status { display: inline-block; cursor: pointer; width: .875rem; height: .875rem; vertical-align: middle; border-radius: 50%; &-primary { background: $--color-primary; } &-success { background: $--color-success; } &-warning { background: $--color-warning; } &-danger { background: $--color-danger; } &-info { background: $--color-info; }}Copy the code
-
Mixin. SCSS – mixin, put some styles here that need to be reused (temporarily empty)
-
Reset. SCSS – Resets the style file. Later we will modify the style directly here (temporarily empty)
-
Variable. SCSS – Defines variables that act as less
// Set some variables $primary-color: #40586F; $success-color: #51cf66; $warning-color: #fcc419; $danger-color: #ff6b6b; $info-color: #868e96; // #22b8cf; $body-bg: #E9EEF3; // #f5f5f9; $sidebar-bg: #F8F9FB; $navbar-bg: #F8F9FB; $font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; Copy the code
-
-
Modify main.js, since we’ve already introduced the Element theme file in index. SCSS, we can remove it
.// Introduce the element-ui theme file, since this file has already been introduced in index. SCSS, there is no need to introduce it here // import 'element-ui/lib/theme-chalk/index.css' // Introduce custom style files import './styles/index.scss'.Copy the code
Share global style variables
If we want to use it in other files, such as vue componentsvariables.scss
, then we need to set the global style variable sharing
Local introduction
// Do not set global sharing, only introduced in a single component
<style lang="scss">
// Import sass files
@import "~@/styles/variables.scss";
// Use style variables
div {
background: $primary-color;
}
</style>
Copy the code
Problem: If there are too many components, they will be referenced multiple times and consume resources. We can set global shared variables
Global Shared
Visit VUC – CLI official website – Guide – Development – CSS related – Pass options to the preprocessor Loader
-
Create the configuration file vue.config.js in the root directory
module.exports = { // CSS configuration items css: { loaderOptions: { // Style compiler type scss: { // Add a line in front of the code before the application reads the SCSS format CSS. Here we introduce the style variable file before each LOAD of SCSS to achieve global sharing // Since we are using the 8.xx version of sass, write prependData, otherwise write additionalData prependData: `@import '~@/styles/variables.scss'; `}}}}Copy the code
-
Run the following command to restart the server
-
After setting up the configuration file above, there is no need to import the file every time you write CSS, WebPack will import it automatically
Process routing functions
Basic Function Settings
The specific requirements
- The initial routing component is set up, and the component structure is written later
- Write the corresponding routing structure to switch the URL to the corresponding component
- Add a layout container component to which the sidebar, top bar, and content display area are all written, and all subsequent components are children of this component
- Add a 404 page to switch to when the user visits a page that doesn’t exist
Creating a file structure
Here we create folders under views according to the sidebar design, one folder for each component, and an index.vue file under each folder
- Login – The login page component
- Layout – The layout container component that wraps all components except the landing page
- Home – Home page component
- Rolelist – rolelist component
- Menu – Menu component
- Resources – Resource list component
- Course – Course management component
- User – User management component
- Advertising – Advertising list component
- Advertising-space – Advertising space management component
Note: Permission management and advertising management do not require routing, but internal secondary menus do
<! </div> </template> <script> export default {name: 'home' } </script>Copy the code
<! -- Layout components, which hold fixed structures and other components, I'm a layout container <router-view></router-view> </div> </template> <script> export default {} </script>Copy the code
Routing rule writing
// Import vue and router
import Vue from 'vue'
import VueRouter from 'vue-router'
// Import the required components
import login from '@/views/login/index'
import layout from '@/views/layout/index'
import home from '@/views/home/index'
import rolelist from '@/views/role/index'
import menu from '@/views/menu/index'
import resources from '@/views/resources/index'
import course from '@/views/course/index'
import user from '@/views/user/index'
import Advertising from '@/views/Advertising/index'
import AdvertisingSpace from '@/views/Advertising-space/index'
import error from '@/views/404/index'
// Import the router as a vue plug-in
Vue.use(VueRouter)
// Set routing rules
// All components except login and 404 are set as child routes for layout
const routes = [{
// Login module, a separate page
path: '/login'.component: login
}, {
path: '/'.component: layout,
// Add child routes to the layout container. All other child routes should be displayed under the layout container
children: [{
// Set homepath to empty, so that/will also display the contents of home, and hone will be the home content after login
path: ' '.component: home
}, {
path: '/role'.component: rolelist
}, {
path: '/menu'.component: menu
}, {
path: '/resources'.component: resources
}, {
path: '/course'.component: course
}, {
path: '/user'.component: user
}, {
path: '/Advertising'.component: Advertising
}, {
path: '/AdvertisingSpace'.component: AdvertisingSpace
}, {
// 404 module, a single page
path: The '*'.component: error
}]
}]
// Create instance vuetouter
const router = new VueRouter({
routes
})
// Export the instance
export default router
Copy the code
The above two basic writing can modify the FUNCTION of the URL suffix switch component
Function optimization
The problem
- If you have a lot of features, the package will be larger because all the components are packed together
- Components that we do not access at load time are also loaded, resulting in inefficiency
- The packaged names are randomly generated, and we want each module name to correspond to the file name
The solution
- Routing lazy loading: routing lazy loading | Vue Router (vuejs.org), which can separate each component to packaging, when access will load the corresponding component
- Use webpack magic comments to set the name of the package file. You can set the name of each package to correspond to the component name for easy function debugging
// Import vue and router
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// Set routing rules
// All components except login and 404 are set as child routes for layout
// Replace all the modules used with lazy-loading routes and use Webpack's magic annotation feature to set the packaged filename prefix
const routes = [{
// Login module, a separate page
path: '/login'.component: () = > import(/* webpackChunkName:'login' */ '@/views/login/index')}, {path: '/'.component: () = > import(/* webpackChunkName:'layout' */ '@/views/layout/index'),
// Add child routes to the layout container. All other child routes should be displayed under the layout container
children: [{
// Set homepath to empty, so that/will also display the contents of home, and hone will be the home content after login
path: ' '.component: () = > import(/* webpackChunkName:'home' */ '@/views/home/index')}, {path: '/role'.component: () = > import(/* webpackChunkName:'role' */ '@/views/role/index')}, {path: '/menu'.component: () = > import(/* webpackChunkName:'menu' */ '@/views/menu/index')}, {path: '/resources'.component: () = > import(/* webpackChunkName:'resources' */ '@/views/resources/index')}, {path: '/course'.component: () = > import(/* webpackChunkName:'coures' */ '@/views/course/index')}, {path: '/user'.component: () = > import(/* webpackChunkName:'user' */ '@/views/user/index')}, {path: '/Advertising'.component: () = > import(/* webpackChunkName:'Advertising' */ '@/views/Advertising/index')}, {path: '/AdvertisingSpace'.component: () = > import(/* webpackChunkName:'AdvertisingSpace' */ '@/views/Advertising-space/index')}, {// 404 module, a single page
path: The '*'.component: () = > import(/* webpackChunkName:'404' */ '@/views/404/index')}}]]// Create instance vuetouter
const router = new VueRouter({
routes
})
// Export the instance
export default router
Copy the code
Layout processing
Set the fixed contents of the module layout in the container module Layout, including the top bar of the sidebar. The content area does not need to be set here (written inside other components). Components here write component
Note: You can refer to the documentation at the bottom of the component page for some of the styling features
- Layout container
- Use the layout container components provided by Element-UI
- The sidebar
- Use the navigation menu component provided by Element-UI
- The top bar
- On the left, use the breadcrumb component from Element
- To the right, use the wlement avatar and drop-down menu component components
Layout container
Set the overall layout of the page. Set the left and right columns here, and then the right column
<template> <! -- Layout container --> <el-container> <! - the sidebar - > < el - value width = "200 px" > sidebar < / el - value > <! -- Right --> <el-container> <! -- Top --> <el-header> top column </el-header> <! </el-main> </el-container> </el-container> </template> <script> export default {} </script> <style lang=" SCSS "scoped> // Set three background colors. El-container {height: 100vh}. } .el-header { background: #fff; } .el-main { background-color: #e9eef3; } </style>Copy the code
The sidebar
The sidebar component is written separately in lauout components > app-aside. Vue
<template> <! Use Element's navigation menu component --> <! -- efault-active="1" By default, select the first navigation class="el-menu-vertical-demo" class name background-color="#545c64" background color text-color="# FFF "text color Active-text-color ="#ffd04b" router <el-menu default-active="1" class="el-menu-vertical-demo" <el-menu default-active="1" class="el-menu-vertical-demo" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" router unique-opened> <! <el-submenu index="1"> <! <template slot="title"> <! < I class="el-icon-location"></ I >< span> Permissions </span> </template> <! -- The actual navigation menu is written in the el-menu-itemgroup el-menu-item --> < el-menu-itemgroup > <! <el-menu-item index="/role"> Role list </el-menu-item> <el-menu-item Index ="/menu"> menu list </el-menu-item> <el-menu-item index="/resources"> Resource list </el-menu-item> </el-menu-item> </el-submenu> <el-menu-item index="/course"> < I class="el-icon menu"></ I >< span slot="title"> </span> </el-menu-item> <el-menu-item index="/user"> < I class="el-icon-document"></ I >< span slot="title"> </span> </el-menu-item> <el-submenu index="4"> <template slot="title"> < I class="el-icon-location"></ I >< span> </span> </template> <el-menu-item-group> <el-menu-item index="/Advertising"> Advertising list </el-menu-item> <el-menu-item Index ="/AdvertisingSpace"> AdvertisingSpace list </el-menu-item> </el-menu-item-group> </el-submenu> </el-menu> </template> <script> export default { } </script> <style> </style>Copy the code
The top bar
The top bar component is written separately in lauout components > app-header.vue
<template> <! <div class="header"> <! Breadcrumb navigation, there's nothing set here, <el-breadcrumb separator-class="el-icon-arrow-right"> <el-breadcrumb-item :to="{path: > </el-breadcrumb-item> </el-breadcrumb-item> <el-breadcrumb-item> Activity list </el-breadcrumb-item> <el-breadcrumb-item> Activity details </el-breadcrumb-item> </el-breadcrumb> <! <span class="el-dropdown "> <span class="el-dropdown "> -- Replace the text with an avatar, Size 35 - > < el - avatar: size = "35" SRC = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" > < / el - avatar > <! - the right arrow -- > < I class = "el - the icon - arrow - down el - icon - right" > < / I > < / span > <! Dropdown menu option, now static value, <el-dropdown-menu slot="dropdown"> <el-dropdown-item> User information </el-dropdown-item> <el-dropdown-item </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> </template> <script> export default {} </script> <style lang=" SCSS "scoped> // Container height, flex layout, center alignment. display: flex; align-items: center; justify-content: space-between; // Display: flex; // Display: flex; // Display: flex; align-items: center; } } </style>Copy the code
The layout container introduces components
Add the sidebar and top sidebar components to lauout index.vue and apply them
<template> <! -- Layout container --> <el-container> <! -- Side bar --> <el-aside width="200px"> <! - the introduction of the sidebar components - > < appAside > < / appAside > < / el - value > <! -- Right --> <el-container> <! -- Top --> <el-header> <! - introduce top bar component - > < appHeader > < / appHeader > < / el - the header > <! -- Content display area --> <el-main> <! -- This is the display area for routing components --> <router-view></router-view> </el-main> </el-container> </el-container> </template> <script> // Import appAside from './components/app-aside' import appHeader from './components/app-header' export default { name: 'layout', components: {// Register two components appAside, appHeader}} </script> <style lang=" SCSS "scoped> 100vh } .el-aside { background-color: #545c64; } .el-header { background: #fff; } .el-main { background-color: #e9eef3; } </style>Copy the code
Interface processing – Encapsulates the request module
Note: We coded the parameters in urlencoded format, the document was wrong, so we had to rewrite the data when we used the POST requestName = value & Name = value....
In the form of
useForeground interface documentationandBackground Interface documentTo get the data, you need to use the AXIos plug-in
-
Install NPM install axiOS for aixOS
-
Create the request folder under SRC > utils
/ / introduce axios import axios from 'axios' // Create an axios instance and set the generic properties const request = axios.create({ // The timeout time is -2s timeout: 2000.// Default prefix baseURL: ' ' }) // The axios interceptor, before the request is initiated request.interceptors.request.use(config= > { // The root determines the incoming URL prefix and sets the different baseURL config.baseURL = /^\/front/.test(config.url) ? 'http://edufront.lagou.com' : 'http://eduboss.lagou.com' // Returns the new configuration object return config }) // Export the instance export default request Copy the code
-
Try using modules
<template> <div id="app"> <router-view /> <! </div> </template> <script> import request from '@/utils/request' // try using the interface module here Request ({// get method: 'get', // get address url: '/ front/course/getAllCourse}). Then (res = > {/ / print the data returned. Take a look at the console log (res)}) export default {} < / script > < style lang="scss"> </style>Copy the code