1. Install node environment

Vue runs on the Node environment. Before building the VUE framework, ensure that the Node environment is installed successfully.

Download the installation package from node.js website and install it for a fool.

After installing Node.js, NPM (package management tool) already comes with it. There is no need to install NPM separately.

The terminal enters a command to check whether the installation is successful. If the version number is displayed, the Node environment is successfully installed

Two, install Taobao image CNPM

The NPM server is foreign, so sometimes we are very slow to install “modules”. Taobao image will be NPM above the module synchronization to the domestic server, improve our module installation time. After the installation of Taobao image, CNPM and NPM command line can be used, the two do not conflict

Open the command line and enter the following command to install CNPM

$ npm install -g cnpm --registry=https://registry.npm.taobao.orgCopy the code

Install webPack

npm install webpack -gCopy the code

Iv. Install vuE-CLI scaffold builder tools

Global installation, command line input

npm install -g vue-cliCopy the code

Run the vue -v command to view the version number. If the version number is displayed, the installation is successful

V. Vue-CLI construction project

Go to your project directory and create a new project based on the WebPack template: vue init WebPack project name

vue init webpack demoCopy the code

Demo is the project name. You can define the name based on your project. After you press Enter, a series of configuration questions will be displayed after the template is downloaded

Description:

  • Project name: indicates the Project name
  • Project Description: Project description
  • Author: the Author
  • Vue Build: Pack (standalone and Runtime), press Enter to select the default
  • Install vue-router? : Whether to install routes? It’s definitely going to be needed. Press y enter
  • Use ESLint to lint your code? : Enable esLint code detection rules? Not currently. Press N Enter
  • Setup unit tests with Karma + Mocha? : Unit testing? Not currently. Press N Enter
  • Setup e2e tests with Nightwatch? : Is end-to-end testing performed? Not currently. Press N Enter

After the configuration is completed, we will see our project file demo in our project directory. We can locate the terminal to the current project and enter the following command line in the command line, and the project is successfully started. To access the project, type localhost:8080 in the browser address bar

npm run devCopy the code

Vi. Introduction to vUE project catalog

1. Build: Build script directory

1) build.js ==> production environment build script;

2) check-versions.js ==> Check the NPM, Node.js version;

3) utils.js ==> build relevant tool methods;

4) Vue-loader.conf. js ==> configures CSS loader and automatically adds prefixes after compiling CSS;

5) webpack.base.conf.js ==> webpack basic configuration;

6) Webpack.dev.conf. js ==> Webpack development environment configuration;

7) Webpack.prod.conf.js ==> Webpack production environment configuration;

2. Config: Project configuration

1) dev.env.js ==> dev environment variable;

2) index.js ==> project configuration file;

3) Prod.env.js ==> production environment variables;

3, node_modules: NPM loaded project dependent modules

4. SRC: Here is the directory we are going to develop. Basically everything we are going to do is in this directory. It contains several directories and files:

1) Assets: resource directory, place some pictures or public JS and CSS. The resources here will be built by WebPack;

2) Components: Directory where we write components;

3) Router: front-end route. The route path we need to configure is written in index.js.

4) app.vue: root component;

5) main.js: entry js file;

5, static: static resource directory, such as images, fonts, etc. Will not be built by Webpack

6, babelrc: Babel compiler parameter

Editorconfig: Code format

8, gitignore: git upload file configuration to ignore

Postcsrc. Js: a tool for converting CSS

Index.html: home page entry file, can add some meta information, etc.

Package. json: NPM package configuration file, which defines the NPM script of the project, dependency packages and other information

Readme. md: Project description document, Markdown format

7. Change the port number

To avoid port conflicts, you can also modify port parameters by opening the config/index.js file

Install the Element-UI framework

[1] Installation

npm install element-ui -SCopy the code

[2] introduced in main.js file

import ElementUI from ‘element-ui’

import ‘element-ui/lib/theme-chalk/index.css’

Vue.use(ElementUI)

Install SASS

[1] Installation

npm install --save-dev css-loader
npm install --save-dev sass-loader
npm install --save-dev style-loader

// Sass-loader depends on Node-sass
npm install --save-dev node-sassCopy the code

[2] Configuration

Configure it in the webpack.base.conf.js folder

rules:[
    ....
    {
        test: /\.sass$/.loaders: ['style'.'css'.'sass']}]Copy the code

[3] Test

Add lang=’ SCSS ‘to the style tag in the component that uses SCSS

In the app.vue file, define a background color variable and apply it to the CSS style. The background turns gray to indicate that SASS has been successfully configured


10. Configure the local proxy

1. Find the config/index.js file in the project to configure proxyTable. After configuration, NPM run dev needs to restart the project

    proxyTable: {
      '/api': {           // Configure the background proxy
        target: 'http://192.168.37.56:8090'.secure: false.pathRewrite: {
          '^/api': ' '
        },
        changeOrigin: true
      },
      "/socket": {       / / configuration webSocket
        target: 'http://192.168.37.56:8090'.secure: false.pathRewrite: {
          '^/socket': ' '
        },
        changeOrigin: true.ws: true}},Copy the code

Description:

  • Target: indicates the domain name IP address of the background interface requested by the local test environment
  • Secure: HTTPS parameters to be configured
  • PathRewrite: instead of the inside of the targe address, such as we need to call “HTTP: 192.168.37.56:8090 / user/add” interface, can be directly written “/ API/user/add”
  • ChangeOrigin: Indicates the parameter to be configured for interzone interface

2. Detailed parsing of config/index.js configuration parameters

'use strict'
const path = require('path')

module.exports = {
  // Development environment
  dev: {
    assetsSubDirectory: 'static'.// Compile the output secondary directory
    assetsPublicPath: '/'.// The root directory for compiling and publishing, which can be configured as the resource server domain name or CDN domain name
    proxyTable: {}, // Configure the background proxy
    host: 'localhost'.// Run the domain name IP of the test page
    port: 8080.// The port to run the test page
    autoOpenBrowser: false.// Whether the browser opens automatically when the project runs
    errorOverlay: true.// Browser error message
    notifyOnErrors: true.// Cross-platform error message
    poll: false.// Use the file system to get notification of file changes devserver.watchoptions
    devtool: 'cheap-module-eval-source-map'.// Add debugging, this property is the original source code
    cacheBusting: true.// Invalidate the cache
    cssSourceMap: true // It is very difficult to locate bugs after code compression. SourceMap is introduced to record the position information before and after compression. When errors are generated, the location is directly located before compression
  },
  // Production environment
  build: {
    index: path.resolve(__dirname, '.. /dist/index.html'), // Compile the input index.html file
    assetsRoot: path.resolve(__dirname, '.. /dist'), // Static resource path to compile output (the file when the project is packaged)
    assetsSubDirectory: 'static'.// Compile the output secondary directory
    assetsPublicPath: '/'.// The root directory for compiling and publishing, which can be configured as the resource server domain name or CDN domain name
    productionSourceMap: true.// Whether to enable cssSourceMap
    devtool: '#source-map'.// Add debugging, this property is the original source code
    productionGzip: false.// Whether to enable gzip
    productionGzipExtensions: ['js'.'css'].// Use the extension of the gzip compressed file
    bundleAnalyzerReport: process.env.npm_config_report // Package analysis}}Copy the code

Xi. Encapsulation of AXIos

[1] Installation

npm install axios --save-devCopy the code

[2] Create a new services folder in the SRC directory of your project, and create an ajax.js and a getData.js file inside. The ajax.js file is used to wrap our AXIos, and the getData.js file is used to unify our interface.

[3] Ajax.js encapsulates AxiOS

import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
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["demo-auth"] = store.state.loginInfo ? store.state.loginInfo.userId : ""; // The userId has been saved in store
    return request;
})

// 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()
    })
})

// The login expires
axios.interceptors.response.use(response= > {
    let data = response.data;
    if([10002].includes(data.ret)
    ) {
        router.then(lib= > lib.default.push({ name: "login" })); // Jump to the login page
        Message.warning(data.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.code === 200) {
            return Promise.resolve({
                data: data.data,
                msg: data.msg,
                code: data.code,
            });
        }
        return Promise.reject(
            data.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.msg ||
        "Network error"
    );
})

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

[4] GetData.js interface management

import { get, post } from "@/services/ajax";

// Get the program configuration
export function getConfig() {
    return get("static/config.json".null, { baseURL: ". /" });
}

// Find the occupied location of the goods
export function queryGoodsLabel(params) {
    return get("/goods/queryGoodsLabel", params);
}

// Replace the occupied position
export function switchLabel(params) {
    return post("/goods/switchLabel", params); }}Copy the code

[5] call in the page

import { queryGoodsLabel, switchLabel } from '@/services/getData.js'
export default {
        data() {
            return{}},methods: {
            changePlace(row) {
                this.params = {
                    id: row.id,
                    customsListNumber: row.customsListNumber,
                }

                // Find the occupied location of the goods
                queryGoodsLabel(this.params).then(res= > {
                    this.$refs.positionDialog.refill(res.data.split(","), true);
                }).catch(err= > {

                })
            },
            change(data) {
                this.params.labels = data.join(', ')

                // Replace the occupied position
                switchLabel(this.params).then(res= > {
                    this.$Message.success('Position changed successfully')
                }).catch(err= > {
                    this.$Message.error(err)
                })
            }
        },
    }Copy the code

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