Recently, the company has come to a new project, the Vue project was built with Vue CLI2 before, now we are going to build with Vue CLI3, this article is to record the actual combat process, if you think this article is helpful, please give a thumbs up, thank you. Updates continue at …………

Install Vue CLI3

  • First you need to uninstall Vue CLI2 with the commandnpm uninstall vue-cli -gUnloading;
  • Type the commandnpm install -g @vue/cliInstall the Vue CLI3;
  • After the installation is complete, enter the commandvue --versionTo check whether the Vue CLI version is 3.0 or later, the installation is successful.

Ii. Set up Vue project

  • Create a new folder, note that the file name should not be in Chinese, according to the following figure;

  • Type the commandvue create flow_manage_platform.flow_manage_platformIs the project name;
  • Press up or down to select Manually select features,default (Babel, esLint) (default installation);

  • Press up and down and Enter keys to select the function to install;

  • To use the router’s history mode, press Enter to go to Next.

  • Select the CSS preprocessor language, select less, and press Enter to go to the next step.

  • Select In dedicated Config files to separate Babel, PostCSS and other configurations from package.json.

  • Whether to save the installation configuration, press Enter to go to the next step.

  • If the following image appears, it is time to download the Vue project;

  • If the download is slow and there is a network problem, you can connect the computer to your mobile network.

Iii. Clean Vue project

The Vue project built through the Vue CLI has a lot of useless files and code that needs to be cleaned.

1. Initialization

  1. When the download is complete, first open the package.json file and set it to
    "scripts": {
        "serve": "vue-cli-service serve",
        "build": "vue-cli-service build"
    },
    Copy the code

    to

    "scripts": {
        "dev": "vue-cli-service serve",
        "build": "vue-cli-service build"
    },
    Copy the code

    Because used in Vue CLI2npm run devCommand to start the project.

  2. usenpm installInstall dependencies. After the dependencies are successfully installed, run thenpm run devAfter the command is successfully executed, open the browserhttp://localhost:8080/, as shown in the following figure, the Vue project has been set up successfully.

2. Clean the index. HTML file in the public file

It is cleaned as follows:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Name ="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %> </head> <body> <div id="app"></div> </body> </html>Copy the code

3. Clean the router.js file

It is cleaned as follows:

import Vue from 'vue'
import Router from 'vue-router';
Vue.use(Router)

function load(component) {
    return resolve => require([`./views/${component}`], resolve);
}

export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/',
            name: 'home',
            component: load('home')
        },
    ]
})

Copy the code

4. Clean app. vue files

It is cleaned as follows:

<template>
  <div>
    <router-view/>
  </div>
</template>
Copy the code

5. Clean the views folder

Delete the about. vue and home. vue files from the Views folder.

Create a new home.vue file. As follows:

Welcome to the Vue project </div> </template>Copy the code

6. Clean the Components folder

Delete the helloWorld.vue file from the Components folder.

7. Clean the Assets folder

Delete the logo. PNG file in the Assets folder.

8. Clean up

Run NPM run dev again, and open http://localhost:8080/ in the browser. If the following figure is displayed, the Vue project is cleaned successfully.

Configure the Vue project

After cleaning, but it still does not meet the requirements of our project development, we need to further configure.

1. Create an API folder

Create a new API folder under the SRC folder and place the axios configuration file axios.js and the interface file.

2. Create a mixins folder

Create a mixins folder under the SRC folder to place Vue mixins files.

In the minxins folder, create an index.js file and place the global mix.

Export default {data() {return {}}, created(){alert(' global chaos introduced successfully ')}, methods: {}}Copy the code

Introducing global mixins in main.js,

import mixins from './mixins';
Vue.mixin(mixins);
Copy the code

In the browser page, you can see that the popover global chaos is successfully introduced, indicating that the introduction is successful.

Return to minxins/index.js file

Created (){alert(' global chaos introduced successfully ')},Copy the code

Deleted!

3. Create the Service folder

Create a service folder under the SRC folder to store public methods and configuration files.

4. Configure the Assets folder

  1. Create a CSS folder under assets to store style files.
  2. Create an images folder under Assets, which contains images that can be compiled.

5. Create a Router folder

Create a router folder under the SRC folder.

Delete the router.js file from the SRC folder.

In the Router folder, create the index.js and routes.js files.

Index. Js content:

import Vue from 'vue'; import Router from 'vue-router'; import routes from './routes'; Vue.use(Router); // Router configuration const router = new router ({mode: 'history', base: process.env.BASE_URL, routes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition; } else { return {x: 0, y: 0}; }}}); router.beforeEach((to, from, next) => { next(); }); router.afterEach((to, from, next) => { window.scrollTo(0, 0); }); export default router;Copy the code

Routes. Js content:

function load(component) { return resolve => require([`views/${component}`], resolve); } const routes = [{path: '/', name: 'home', Component: load('home'), meta: {title: 'home'}, {path: '*', redirect: { path: '/' } } ]; export default routes;Copy the code

6. Create a store folder

Create a store folder under SRC and place the Vuex content.

Delete the store.js file from SRC folder.

Create a new module folder under the Store folder,

Create a new demo.js file in the Module folder.

Const state = {moduleTip: 'Welcome to Vuex ',}; const getters = { moduleTip: state => state.moduleTip, }; const mutations = { SET_MODULETIP(state, data) { state.moduleTip = data; }}; const actions = {}; export default { state, getters, mutations, actions }Copy the code

Create a new index.js file in the Store folder.

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const debug = process.env.NODE_ENV ! == 'production'; import demo from './module/demo'; Const store = new Vuex.Store({strict: debug, state: {tip: 'Welcome to Vuex',}, getters: {tip: state => state.tip, }, mutations: { SET_TIP(state, data) { state.tip = data; }, }, actions: { }, modules: { demo, } }); export default store;Copy the code

To the minxins/index.js file,

import { mapGetters } from 'vuex'; export default { data() { return { } }, computed: { ... mapGetters(['tip','moduleTip']) }, mounted(){ }, methods: { } }Copy the code

In the views/home.vue file,

<template> <div> Welcome to Vue project {{tip}} {{moduleTip}} </div> </template>Copy the code

Display on the browser page:

Welcome to Vue project welcome to Vuex welcome to Vuex moduleCopy the code

The global Vuex and module Vuex are successfully configured.

7. Alias of the configuration file

In Vue CLI3, the webpack configuration of the project is to be configured by creating vue.config.js in the root directory.

The configuration content in the vue.config.js file is as follows:

const path = require('path');
function resolve(dir) {
    return path.resolve(__dirname, dir)
}
module.exports = {
    configureWebpack: {
        resolve: {
            extensions: ['.js', '.vue', '.json'],
            alias: {
                '@': resolve('src'),
                'assets': resolve('src/assets'),
                'css':resolve('src/assets/css'),
                'images':resolve('src/assets/images'),
                'views': resolve('src/views'),
                'components':resolve('src/components'),
                'api':resolve('src/api'),
                'mixins':resolve('src/mixins'),
                'store': resolve('src/store'),
                'service':resolve('src/service'),
            }
        }
    },
}
Copy the code

8. Close source Map

Closing the Source Map has two benefits

  1. Reduce packaging compilation time;
  2. Avoid seeing source code in Sources with the F12 developer tools in production.

The configuration content in the vue.config.js file is as follows:

module.exports = {
    productionSourceMap: false,
}
Copy the code

9. Configure devServer

  1. Fixed port

    Sometimes a fixed port is required for setting a cross-domain whitelist at the back-end, and a fixed port is required at the front-end. Port: 8036,

  2. Enabling Hot Update

    hot: true,

  3. Fixed opening browser

    open: 'Google Chrome',

The configuration content in the vue.config.js file is as follows:

module.exports = {
    devServer:{
        port: 8036,
        hot: true,
        open: 'Google Chrome'
    }
}
Copy the code

Reset CSS style

Create the base.less file in the SRC /assets/ CSS folder.

The file content is as follows: base.less

Write to main.js

import 'css/base/base.less';
Copy the code

5. Introduce the Element-UI component library

  1. Installing dependency packages

    Run the NPM I element-ui-save command

  2. The introduction of the style

    Insert the following code before new Vue in main.js

    import 'element-ui/lib/theme-chalk/index.css';
    Copy the code
  3. Complete introduction of the Element-UI component library (one of two options)

    If most of the elements in the Element-UI are used in your project, it is recommended to include them in their entirety

    Insert the following code before new Vue in main.js

    import ElementUI from 'element-ui';
    Vue.use(ElementUI);
    Copy the code
  4. Introduce the Element-UI component library on demand (one of two options)

    Take the example of introducing the Button Button component

    • Insert the following code before new Vue in main.js

      Import {Button,} from 'element-ui'; const components = [ Button, ]; for (let k of components) { Vue.use(k); }Copy the code
    • In the SRC /views/home.vue file

      <template> <div> Welcome to Vue project {{tip}} {{moduleTip}} <el-button> Hungry button component </el-button> </div> </template>Copy the code
    • If the following image is displayed on the browser page, the import on demand is successful

5. Customize themes (batch change element component styles)

  • Because element is written using Sass, you need to install sass and sass-loader first, and run the NPM I sass sass-loader -d command.

  • In the SRC /assets/ CSS /base folder, create element_theme. SCSS and element_var. SCSS (theme style variables);

    • element_theme.scss
    • element_var.scss
  • In main.js, import ‘CSS /base/element_theme.scss’;

  • In the SRC /views/home.vue file

    {{tip}} {{moduleTip}} <el-button type="primary"> </el-button> </div> </template>Copy the code
  • Press F12 to open the developer tool and review the elements as shown below

  • Search in the element_var. SCSS file#4574d0, you can see the following figure. Replace it with$--color-primary: red ! default;

  • The browser page displays the theme successfully as shown in the following figure

Install Jquery Js library

Although Vue manipulates DOM with data. However, there are some situations where it is convenient to use Jquery, such as getting the height of an element and dynamically changing the height of a table to keep the head fixed.

  • Execute the commandnpm i Jquery -save
  • Add code to vue.config.js:
    const webpack = require('webpack');
    module.exports = {
        configureWebpack: {
            plugins: [
                new webpack.ProvidePlugin({
                    $:"jquery",
                    jQuery:"jquery",
                    "windows.jQuery":"jquery"
                })
            ]
        },
    }
    Copy the code
  • Add new code to main.js:
    import $ from 'jquery';
    Copy the code
  • SRC /views/home.vue
    <template> <div class="p-wrap"> Vue project {{tip}} {{moduleTip}} <el-button type="primary"> </template> <script> export default {mounted(){$(".p-wrap").click(function(){alert('Jquery installed successfully ')}); } } </script>Copy the code
  • Click the text on the browser page and the “Jquery installed successfully” dialog box is displayed, indicating that the Jquery Js library is installed successfully

7. Pits for less-loader

If the version of less loader is 4.1.0, install less 2.7.3. Otherwise, less loader will appear

The ERROR in the. / SRC/home/index. The less (. / node_modules / _css - [email protected] @ CSS - loader! . / node_modules / _less - [email protected] @ less - loader/dist/CJS. Js! ./ SRC /home/index.less) Module build failed (from./node_modules/[email protected]@less-loader/dist/cjs.js):Copy the code

An error

Install jS-cookie plug-in

  • This plug-in is mainly used to store, obtain, and remove browser cookies, and is most commonly used to store the token returned by the backend after a successful login.
  • Execute the commandnpm i js-cookie --save
  • Create a cookie.js file under the SRC /service file and write to the file
    import Cookies from 'js-cookie';
    const TokenKey = 'token';
    export function getToken() {
       return Cookies.get(TokenKey);
    }
    export function setToken(token, time) {
       return Cookies.set(TokenKey, token, {
          expires: time,
          path: '/'
       });
    }
    export function removeToken() {
       return Cookies.remove(TokenKey);
    }
    Copy the code

Configure AxiOS

  • Run the NPM I axios-save command

  • Create a new axios.js file in the SRC/API folder

  • Configure axios in axios.js

    • Create a new instance of axios,axios.create([config]),

      Main configuration

      Timeout Specifies the number of milliseconds in which the request will timeout (0 indicates no timeout).

      Headers custom request headers. This configuration must be consistent with that of the backend. Otherwise, the backend will not receive your parameters

      BaseURL configures the backend request address to be automatically prefixed to the URL, making the URL available to the relative address

      import axios from 'axios';
      const service = axios.create({
          timeout: 60000,
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
              "X-Requested-With": "XMLHttpRequest",
          },
          baseURL: 'xxx',
      });
      Copy the code

      In the configuration above, the data format transmitted from the front end to the back end is Form format or JSON format, for example:

      //Form format let data = new URLSearchParams(); data.append("page", currentPage); //JSON format let obj = new Object; obj.page=currentPage;Copy the code

      If the back end is JAVA, the Form format is generally used

      But to pass binary data to the back end, use FormData format, for example:

      let data = new FormData();
      data.append("page", currentPage);
      Copy the code

      Then create a new instance of Axios

      const serviceForm = axios.create({
          timeout: 60000,
          headers: {
              'Content-Type': 'multipart/form-data; charset=UTF-8',
              "X-Requested-With": "XMLHttpRequest",
          },
          baseURL: 'xxx',
      });
      Copy the code
    • Configure the HTTP Request interceptor

      Intercepts requests before they are processed by THEN or catch

      Axios. Interceptors. Request. Use (function (config) {/ / what to do before sending a request return config. }, function (error) {return promise.reject (error); });Copy the code

      In general projects, token is added to the request header here, as follows

      import { getToken } from 'service/cookie'; Let request = function (config) {const token = getToken(); If (token) {// Check whether the token exists. If so, add config.headers. Token = token to each HTTP header. } return config; };Copy the code

      Token in the preceding config.headers. Token is the parameter that the backend tells you to add the token to the header. The backend also needs to configure headers to allow the parameter with the token.

      Write a request for error interception

      Let request_err = function (err) {return promise.reject (err); };Copy the code

      Use these request interceptors for each instance

      service.interceptors.request.use(request, request_err);
      serviceForm.interceptors.request.use(request, request_err);
      Copy the code
    • Configure the HTTP Response interceptor

      Intercepts responses before they are processed by then or catch.

      / / add the response interceptor axios. Interceptors. Response. Use (function (response) {/ / do something to return the response to the response data; }, function (error) {return promise.reject (error); });Copy the code

      General projects are here to return data to do preprocessing and error batch processing, similar tips.

      Intercept until the response is successful

      import { Message } from 'element-ui'; let response = function (res) { const data = res.data; Const message = ` ${data. Code}, ${data. MSG} ` | | 'unknown error if (res) status = = 200) {if (200) data. Code = = {return data. } else { Message({ message: message, type: 'error', }) } } };Copy the code

      The above data.code and data. MSG are negotiated with the back end

      Intercept processing before a response fails

      let response_err = function (err) { if (err.response) { const data = err.response.data; Const message = ` ${data. Code}, ${data. MSG} ` | | 'unknown error message ({message: the message, type: 'error', }) } return Promise.reject(err); };Copy the code

      Use these Response interceptors for each instance

      service.interceptors.response.use(response, response_err);
      serviceForm.interceptors.response.use(response, response_err);
      Copy the code

      Finally, two instances of Axios are exposed

      There are two ways to do this

      One is to hang directly under the Window object, so that you can use service and serviceForm directly in other files

      window.service = service;
      window.serviceForm = serviceForm;
      Copy the code

      Import {service,serviceForm} from ‘API /axios’

      export {service,serviceForm}
      Copy the code
    • Import the AXIos configuration file in the main.js file

      import 'api/axios'
      Copy the code
    • Create a demo.js file in the SRC/API folder and instantiate the request writing methods of POST, GET, and GET with parameters

      Export function get() {return service.get(' API /get'); } /* export function get2(data) {return service.get(' API /get2', {params: data}); } /* export function post(data) {return service.post(' API /post', data); }Copy the code
    • Use in SRC /views/home.vue

      import * as API from 'api/demo';
      export default {
          methods: {
              get() {
                  API.get().then(res => {
                  }).catch(err => {
                  })
              },
              get2() {
                  let data =new URLSearchParams;
                  data.append('param',1)
                  API.get2(data).then(res => {
                  }).catch(err => {
                  })
              },
              post() {
                  let data =new URLSearchParams;
                  data.append('param',1)
                  API.post(data).then(res => {
                  }).catch(err => {
                  })
              }
          }
      }
      Copy the code

The last

Attach the project address