A, install,
[1.1] Install Node
3. X requires Node.js version 8.9 or later. Click here to install Node
After installing Node, type the following command line to query your Node version:
node -vCopy the code
If the current version is not enough, you can enter the following command line to update the Node version to the latest stable version
NPM cache clean -f then install the NPM module: NPM install -g n Upgrade Node. js to the latest stable version: n stable If it is a MAC, add sudo in front of the command: sudo n stableCopy the code
[1.2] Uninstall the old version
If you have installed an older version of VUE-CLI globally, you need to uninstall it first
npm uninstall vue-cli -gCopy the code
[1.3] Install vuE-CLI3
Vue - cli3 / / installation
npm install -g @vue/cli
// Check the version number after installationVue -v or vue --versionCopy the code
2. Create a project
[2.1] Create project command
vue create project // project is the name of the projectCopy the code
[2.2] Select template
- Default (Babel, eslint): The default configuration, only Babel and eslint, the rest must be configured separately
- Manually select features: manual configuration
With the up and down arrows, you can switch options. Here we choose manual configuration
[2.3] Select the configuration
Choose configurations based on your project needs
- The * in parentheses means selected
- Up and down arrows toggle options
- The Space bar is toggled between checked and unchecked
- The A key is toggle all selected and all unselected
- The I key is reverse selection
- Enter Confirms that the selection is complete
Babel, Router, Vuex, CSS preprocessor, Linter/Formatter format check
Ask again if you want to save the configuration:
1) Whether to use histroy mode of routing (Yes)
2) Select a CSS preprocessor (Sass/SCSS)
3) Select an ESLint configuration (ESLint + Standard Config)
4) Select when to run ESLint code rule checking (Lint on Save)
5) In dedicated config files Babel, postCSS, esLint
6) Whether to save the default configuration (Yes)
Selecting Yes will let you fill in the name of a default file that you can use the next time you create a VUE project without having to configure it.
[2.4] Generate directory structure
- Node_modules: This folder contains the dependencies we need for our project;
- Public: static folder. Resources in this folder will not be compiled by WebPack and will be copied directly when building production packages.
- Assets: are static resources used in pages and components, such as public style files, font files, images, etc. The difference between this folder and public is that the resources in this folder will be compiled by Webpack.
- Components: folder to hold our components;
- Views: Folder to store our pages;
- App.vue: This file is the top-level file for all of our vUE pages;
- Main.js: is the entry file for our entire project;
- Router. js: is the routing configuration file.
- Store. js: is a vuex configuration file;
- .browserslistrc: the file is used to set the browser version range for the developer;
- .eslintrc.js: eslint configuration file;
- .gitignore: files to be ignored by Git;
- Babel.config. js: configuration tool for Babel;
- Package-lock. json: Records the relationships and versions of dependencies in the project, preventing NPM packages from complying with “the same library package with the same large version number, and its interface meets the requirements of compatibility”.
- This specification leads to errors in project operation;
- Package. json: describes the project, including the project name, dependent version, author, command, and import file.
- Readme. md: project documentation, project introduction, License, commands (e.g., start command, package command, unit test command, etc.)
The differences between vuE-CLI3 and VUE-CLI2 are as follows:
- Create the project vue Create
- Start project changed from NPM run dev to NPM Run serve
- The config file directory and build folder are removed. If you need to customize the configuration, you need to create the vue.config.js file
- Static resources are moved to the public directory. You can use /xx.xx to access static resources, and move index.html to public
- The views folder has been added to the SRC folder for sorting view components and public components
- The Node-Model folder is automatically downloaded when the project is installed
[2.5] Start the project
npm run serveCopy the code
Modify the directory structure
Because the current directory structure is not conducive to the later development, we now add part of the file, to be able to carry out subsequent function expansion. Under SRC: create API folder, Router folder, utils folder, Views folder, Store folder. Create subdirectories under its files. For details, please refer to the directory screenshot:
Iv. Project configuration vue.config.js
Vue-cli3.0 build project directory does not have build and config directories, so the question is, how do we develop our project? Add vue. Config. js to the root directory of the project. Note that the root directory is not SRC, and it will be automatically loaded by @vue/cli-service. Refer to the Vue CLI
The configuration is as follows:
// vue.config.js
const path = require('path');
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
// The base URL for deploying the application package, which defaults to '/'
// If your application will be deployed at the root of the domain name, for example, https://www.vue-cli.com/, set it to "/".
// If your application is deployed under a subpath, then you need to specify the subpath here. For example, if you are deployed at https://www.my-vue.com/my-app/; So change this value to "/my-app/"
publicPath: "/".Directory of the production environment build files generated when vue-cli-service build is run. Note that the target directory is cleared before building (passing --no-clean at build time turns this behavior off).
outputDir: "dist".// The directory where static resources (js, CSS, img, fonts) are generated.
assetsDir: "".// Specify the output path of the generated index.html
indexPath: "index.html".// By default, generated static resources include hash in their file names for better cache control. However, this also requires that the HTML for index be automatically generated by the Vue CLI. If you cannot use index HTML generated by the Vue CLI, you can turn off file name hashing by setting this option to false
filenameHashing: true.// Build multi-page application, page configuration
pages: {
index: {
// Page entry
entry: 'src/main.js'.// Template source
template: 'public/index.html'.// Output in dist/index.html
filename: 'index.html'.// When using the title option,
/ / title of the template tag needs to be < title > < % = htmlWebpackPlugin. Options. The title % > < / title >
title: 'Index Page'.// The blocks contained in this page are contained by default
// The extracted generic chunk and Vendor chunk.
chunks: ['chunk-vendors'.'chunk-common'.'index']},// When using the entry only string format,
// The template will be derived to 'public/subpage.html'
// And if it can't be found, go back to 'public/index.html'.
// The output file name is derived to 'subpage.html'.
// subpage: 'src/subpage/main.js'
},
// Whether to use eslint-loader in the development environment to save lint code each time. This value will take effect after @vue/cli-plugin-eslint is installed.
// When set to true, eslint-loader prints lint errors as compilation warnings. By default, warnings are only printed to the command line and do not cause compilations to fail.
// If you want Lint errors to appear directly in the browser at development time, you can use lintOnSave: 'error'. This forces eslint-Loader to print Lint errors as compilation errors, which also means that lint errors will cause compilation to fail.
lintOnSave: false.// Whether to use the Vue build with the runtime compiler. Setting this to true allows you to use the template option in Vue components, but this will add an extra 10KB or so to your application.
runtimeCompiler: false.// By default babel-loader ignores all files in node_modules. If you want to explicitly translate a dependency through Babel, you can list it in this option.
transpileDependencies: [],
// If you don't need the source map for production, set it to false to speed up production builds.
productionSourceMap: true.// is a function that takes a Webpack-chainableconFig instance. Allows for more fine-grained changes to the internal WebPack configuration.
chainWebpack: (config) = > {
// Configure the alias
config.resolve.alias
.set(The '@', resolve('src'))
.set('assets', resolve('src/assets'))
.set('components', resolve('src/components'))
.set('router', resolve('src/router'))
.set('utils', resolve('src/utils'))
.set('store', resolve('src/store'))
.set('views', resolve('src/views'))},// Whether thread-loader is used for Babel or TypeScript. This option is automatically enabled when the system CPU has more than one kernel and only applies to production builds.
parallel: require("os").cpus().length > 1.// Pass options to the PWA plug-in.
// https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
pwa: {},
// All webpack-dev-server options are supported. Note: some values like host, port, and HTTPS may be overridden by command line arguments.
// Some values like publicPath and historyApiFallback should not be modified because they need to be synchronized with the publicPath of the development server to work properly.
// Proxy configuration
devServer: {
host: "0.0.0.0".port: 8080./ / the port number
https: false.// https:{type:Boolean}
open: true.// Configure automatic startup browser Open: 'Google Chrome'- default startup for Google
// Configure a single agent
// proxy: 'http://localhost:9000'
// Configure multiple agents
proxy: {
"/api": {
// target: "https://127.0.0.0:8080", // target host
target: "https://mock.yonyoucloud.com/mock/5708".ws: true.// Proxy WebSockets
changeOrigin: true.// Allow WebSockets across domains
pathRewrite: {
"^/api": ""}}}},// Third-party plug-in options
// This is an object that does not perform any schema validation, so it can be used to pass any third-party plug-in options.
pluginOptions: {
foo: {
/ / the plugin can be used as a ` options. PluginOptions. Foo ` access these options.}},// Sometimes you want to pass options to the webpack preprocessor loader. You can use the css.loaderoptions option in vue.config.js. For example, you can pass shared global variables to all Sass/Less styles like this
css: {
loaderOptions: {
// Pass options to sas-loader
sass: {
prependData: ` @import "@/assets/css/common.scss"; @import "@/assets/css/mixin.scss"; @import "@/assets/css/reset.scss"; @import "@/assets/css/var.scss"; `}}}};Copy the code
Global style references
During project development, we often need global style references, such as theme colors, which can become cumbersome to write every time. Since we should have sASS precompiled, we can apply its features boldly. Variables, functions, mixins, etc. But we need global configuration in the project to be effective. Without introducing styles on every page, you can reference them directly.
[5.1] Create a directory
Add the CSS folder under assets and create the following style code files under the CSS folder. Configure the specific codes by yourself
Common. SCSS mainly stores common styles mixin. SCSS mainly stores mixed styles reset. SCSS mainly stores reset styles.varSCSS mainly stores variablesCopy the code
[5.2] Global introduction
In the vue.config.js configuration file, add the following code
module.exports = {
css: {
loaderOptions: {
// Pass options to sas-loader
sass: {
prependData: ` @import "@/assets/css/common.scss"; @import "@/assets/css/mixin.scss"; @import "@/assets/css/reset.scss"; @import "@/assets/css/var.scss"; `}}}},Copy the code
Package configuration
In the actual project development, we often experience project development phase, testing phase, online pre-release stage and final stage, each stage may be different to the requirement of the project code, so how we can function under the different stages to make our project present different effect, use different functions? This is where the concept of environment comes in. As developers, we may need to write some different code for each environment and make sure it runs in the right environment, which requires proper environment configuration and management.
Typically, a project will have the following four environments:
- Development environment (development phase, local development version, usually with some debugging tools or additional accessibility)
- Test environment (during the test phase, the pre-launch version, except for some bug fixes, will not be much different from the launch version)
- Pre-release environment (in the upcoming launch stage, the pre-launch version, the possibility of online problems predicted, no different from the launch version)
- Production environment (during the launch stage, the version officially released will be optimized and error reporting will be turned off)
Notes on environment variables:
- Environment files are placed in the root directory
- The environment name should be consistent with the environment file
- All environment variables except baseUrl and NODE_ENV start with VUE_APP
Create 4 new folders in the root directory of your project for development environment (.env.dev), test environment (.env.test), pre-release environment (.env.pre), and production environment (env.prod).
The.env.dev file contains the following contents:
NODE_ENV = 'development'
VUE_APP_CURRENTMODE = 'dev'
VUE_APP_BASEURL = 'Local Development API Address'Copy the code
The.env.test file contains the following contents:
NODE_ENV = 'test'
VUE_APP_CURRENTMODE = 'test'
VUE_APP_BASEURL = 'Test environment API Address'Copy the code
The.env.pre file contains the following contents:
NODE_ENV = 'pre-release'
VUE_APP_CURRENTMODE = 'pre'
VUE_APP_BASEURL = 'Pre-release environment API address'Copy the code
The env.prod file contains the following contents:
NODE_ENV = 'production'
VUE_APP_CURRENTMODE = 'prod'
VUE_APP_BASEURL = 'Official Environment API Address'Copy the code
Package. Json configuration:
"scripts": {
"dev": "vue-cli-service serve"."build:test": "vue-cli-service build --mode test"."build:per": "vue-cli-service build --mode pre-release"."build:prod": "vue-cli-service build --mode production"."build": "vue-cli-service build"."lint": "vue-cli-service lint"
},Copy the code
Finally, package according to the above configuration:
- NPM run dev // Run locally
- NPM run build:test // Test environment package
- NPM Run Build: Pre // Pre environment package
- NPM run build:prod // Formal environment package
Note:
Use proccess.env.node_env in vue.config.js to access it
// vue.config.js
console.log(process.env.NODE_ENV); // development (output in terminal)Copy the code
NPM run dev dev dev dev dev dev dev dev dev dev dev dev dev dev dev dev dev
"scripts": {
"dev": "vue-cli-service serve --mode test",}// --mode test changes the mode configuration item in Webpack 4 to test, and it reads the configuration in the corresponding.env.[model] file
// If no configuration file is found, the default environment development is used
// Also vue-cli-service build uses the default production environmentCopy the code
7. Use iView for installation
[7.1] Install iView
npm install iview -SCopy the code
[7.2] main.js introduces iView
import iview from ‘iview’
import ‘iview/dist/styles/iview.css’
Vue.use(iview)
8. Axios encapsulation
For vue projects, we usually use the AXIos library, a Promise-based HTTP library that runs in both the browser and Node.js. It has great features such as request and response interception, request cancellation, JSON conversion, client-side XSRF defense, and more. So our company has abandoned the maintenance of its official library vue-Resource and recommended the axios library instead. If you still don’t know axios, you can follow the Axios Instructions in Chinese
[8.1] Installation
npm install axios --save-devCopy the code
[8.2] Create a directory
Create a new API folder in the SRC directory and create a new axios.js and a new getData.js file. The axios.js file is used to encapsulate our AXIos, and getData.js is used to unify our interface.
[8.3] Axios.js encapsulates AXIos
import axios from "axios";
import { Message } from "iview";
let router = import("@/router");
axios.defaults.baseURL = "/api";
axios.defaults.headers.post["Content-Type"] = "application/json; charset=UTF-8";
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers["Cache-Control"] = "no-cache";
axios.defaults.headers["pragma"] = "no-cache";
let source = axios.CancelToken.source();
// Request to add token
axios.interceptors.request.use(request= > {
request.headers["Authorization"] = window.localStorage.getItem('token')?window.localStorage.getItem('token') : "";
return request;
});
// Login expired (the token is invalid) The login page is displayed
axios.interceptors.response.use(response= > {
let data = response.data;
if (
data.state && [401].includes(data.state.code)
) {
router.then(lib= > {
if (lib.default.currentRoute.name === "login") return;
lib.default.push({
name: "login"
})
Message.warning(data.state.msg);
});
}
return response;
})
// Return value destruct
axios.interceptors.response.use(response= > {
let data = response.data;
let isJson = (response.headers["content-type"] | |"").includes("json");
if (isJson) {
if (data.state && data.state.code === 200) {
return Promise.resolve({
data: data.data,
msg: data.state.msg,
code: data.state.code,
page: data.page
});
}
return Promise.reject(
data.state &&
data.state.msg ||
"Network error"
);
} else {
return data;
}
}, err => {
let isCancel = axios.isCancel(err);
if (isCancel) {
return new Promise((a)= > {});
}
return Promise.reject(
err.response.data &&
err.response.data.state &&
err.response.data.state.msg ||
"Network error"
);
})
// Switch the page to cancel the request
axios.interceptors.request.use(request= > {
request.cancelToken = source.token;
return request;
});
router.then(lib= > {
lib.default.beforeEach((to, from, next) = > {
source.cancel()
source = axios.CancelToken.source();
next()
})
})
export function post(url, data, otherConfig) {
return axios.post(url, data, otherConfig);
}
export function get(url, data, otherConfig) {
return axios.get(url, {
params: data, ... otherConfig }); }Copy the code
[8.4] GetData.js interface management (example)
import {get, post } from "./axios";
// Get the program configuration
export function getConfig() {
return get("static/config.json".null, { baseURL: ". /" });
}
// Obtain user information (unified authentication login user)
export function getLoginInfo() {
return get("/oauth/getLoginInfo");
}
/ / login
export function login(params) {
return post("/oauth/login", params);
}
/ / exit
export function logout(params) {
return get("/oauth/logout", params);
}Copy the code
[8.5] Page Call interface (example)
import { login } from "@/api/getData.js";
export default {
data() {
return {
userName: ' '.password: ' '
};
},
methods: {
async login() {
try {
this.loading = true;
let { msg } = await login({
userName: this.userName,
userPwd: this.password
});
this.$Message.success(msg);
this.$router.push({ name: "loginPage" });
} catch (e) {
this.$Message.warning(e);
} finally {
this.loading = false; }}}};Copy the code
Ix. Login Interception (Permission Control)
Vue + Router + AXIOS Implementation of Background Management System login interception (Permission control)
X. GitHub address of the project
vue-iview3-admin
The article is updated every week. You can search “Front-end highlights” on wechat to read it in the first time, and reply to [Books] to get 200G video materials and 30 PDF books