Vue CLI3 construction project initial

1. Install Vue CLI3

1. Run NPM install -g@vue /cli

2. After the installation is complete, run the vue –version command to check whether the Vue CLI version is 3.0 or later.

2. Create projects

1. Run vue create XXX in CMD. Xx indicates the project name

2. Select, anselect features (manually select features) or default (Babel, esLint) (default setup); Here I choose Anally

3. Select Babel, Router, vuex, CSS. Route selection history mode, CSS preprocessor for less language select In Dedicated Config files, Babel, PostCSS and other configurations In package.json file. Whether to save the installation configuration. Choose not to.

3. Clean up the initialization scaffolding project.

1. Package. The json file

Original code block:

"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

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

<! 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

import Vue from 'vue' import Router from 'vue-router'; 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

<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. Welcome to vue project is displayed, indicating that the vue project has been cleaned successfully.

4. Configure the Vue project

1. Create the API folder and utils folder

npm i axios -save

Optimization of AXIos encapsulation inside Utils

/** * import axios from 'axios'; import router from '.. /router'; import store from '.. /store/index'; import { Toast } from 'vant'; // const tip = MSG => {Toast({message: MSG, duration: 1000, forbidClick: true }); } /** * jump to the login page */ const toLogin = () => {router.replace({path: '/login', query: { redirect: router.currentRoute.fullPath } }); } @param {Number} status Status of a failed request */ const errorHandle = (status, Other) => {// Status code Check switch (status) {// 401: not logged in, jump to the login page case 401: toLogin(); break; // 403 Token expired // Clear the token and jump to the login page case 403: tip(' Login expired, please log in again '); localStorage.removeItem('token'); store.commit('loginSuccess', null); setTimeout(() => { toLogin(); }, 1000); break; // 404 request not found case 404: tip(' Requested resource not found '); break; default: console.log(other); Var instance = axios.create({timeout: 1000 * 12}); / / set the post request header instance. Defaults. Headers. Post [' the content-type '] = 'application/x - WWW - form - urlencoded'; / * * * request interceptor * before every request, if there is a token is carried in the request header token * / instance. The interceptors. Request. Use (config = > {/ / login process control, Check the login status of the user according to whether the local token exists // Even if the token exists, the token may be expired, so the request header carries the token. // The background checks the login status of the user according to the token carried. And gives us the corresponding status code // and then we can do some uniform operations based on the status code in the response interceptor. const token = store.state.token; token && (config.headers.Authorization = token); return config; }, Error = > Promise. The error (error)) / / response interceptor instance. The interceptors. Response. Use (a/res/request success = > res. Status = = = 200? Promise.resolve(res) : promise.reject (res), error => {const {response} = error; ErrorHandle (response.status, response.data.message); errorHandle(response.status, response.data.message); return Promise.reject(response); } else {// Handle the disconnection situation // network state in app.vue controls a global disconnection prompt component display hide // About the disconnection component refresh to retrieve data, If (! window.navigator.onLine) { store.commit('changeNetwork', false); } else { return Promise.reject(error); }}}); export default instance;Copy the code

Index.js for API folder

/** * import test from '@/ API /test' // Export default {test, //...... }Copy the code

Interface corresponding to the test module

Import axios from '@/utils/ HTTP '// import axios instance created in HTTP const test = {// newlist test() {return axios.post(`/api/demo1`).then((res) => { return res.data }) }, } export default test demo.vue this.$api.test.test().then(res => { console.log(res); })Copy the code

Finally, to facilitate API calls, we need to mount it on the vue prototype. In the main. In js:

$prototype.$API = API; // Mount the API to the vue prototypeCopy the code

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.

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

Introducing global mixins in main.js,

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

3. 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.

4. 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:

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

5. 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.

​ demo.js:

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: </div> Welcome to Vue project {{tip}} {{moduleTip}} </div> </template>Copy the code

The page says “Welcome to Vue project Welcome to Vuex Welcome to Vuex module “.

Reset CSS style

Create a reset. less file in the SRC/Assets/CSS folder and find an initialization style file online

Write to main.js

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

7. Alias of the configuration file

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'),}}},} // Avoid using F12 developer tools to see source code in Sources in production. Module.exports = {productionSourceMap: // exports = {productionSourceMap: // exports = {productionSourceMap: false, } //npm i Jquery -save const webpack = require('webpack') module.exports = { configureWebpack: { plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'windows.jQuery': 'jquery',}),],},} // Proxy target indicates that the interface has IP (domain name), API is the prefix used locally. Module. exports = {devServer: {host: 'localhost', port: '8083', proxy: {'/ API ': {// // API: 'https://www.fastmock.site/mock/fd7892a0bc009dd928228bb6dba37099/test', / / cross domain domain changeOrigin: true, / / whether open cross-domain secure: PathRewrite: {// rewrite path '^/ API ': ', // change/API to null characters},},},},},}Copy the code

8. Attach the main.js file

import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import Mixins from '. / mixins import $from 'jquery import API from'. / API / / import API interface import 'swiper/dist/CSS/swiper. Min. CSS'  // import 'swiper/dist/js/swiper.min' // Vue.mixin(mixins) Vue.config.productionTip = false Vue.prototype.$api = api // New vue ({router, store, render: (h) => h(App),}).$mount('# App ')Copy the code
Set the content of the following two articles, the author: the world of mortals refined heart link: https://juejin.cn/post/6844903912097464334 source: the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source. Source: author: grid bear links: https://juejin.cn/post/6844903969152565261 the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code