Vue development summary and some best practices (Updated)

Keywords: Javascript Vue axios less JSON

Basic development environment

Project created by vue-cli3, vscode as a coding tool
vscode plug-in recommendations: vscode plug in configuration

Article directory

  1. Introduction to project directory structure
  2. UI framework selection
  3. main,js processing
  4. Axis request secondary encapsulation

1. Project directory structure

├── public // index.html
├── src // Business related
│ ├── assets // Static files (css, images)
│ ├── components // Global component
│ ├── layouts // Basic style layout
│ ├── plugin // Introduction of styles and tools
│ ├── request // Request configuration
│ ├── router // Route
│ ├── store // Global state management
│ ├── utils // Tool file
│ ├── app.vue // Entry file
│ ├── main.js // Primary profile
│ └── views // page
├── .eslintrc.js // eslint check configuration
├── .env.release // Test environment variables
├── .env.pre-build // Advance environment variable
└── vue.config.js // webpack packaging configuration

2. UI framework selection

element, iview, ant design Vue
Finally, ant design Vue, portal https://vue.ant.design/docs/vue/introduce-cn/

Advantage:

    1. Good-looking
    1. Clear document

      1. Easy to use, clear examples
    2. Fewer bug s, smooth use of components
    3. Good performance, single case test

    3. main.js processing

    main.js as the operation entry, many things need to be introduced, the code volume is too large, and needs to be deleted

    import Vue from 'vue'
    import App from './App.vue'
    import router from '@/router'
    import store from '@/store'
    import * as filters from '@/utils/filters'   // Global filter
    import './plugin'    // Import operation set
    import './assets/css/index.less'  // Style set
    Vue.config.productionTip = false
    
    // Global filter
    Object.keys(filters).forEach(key => {
      Vue.filter(key, filters[key])
    })
    
    // Non parent-child component value transfer bus
    Vue.prototype.$bus = new Vue()
    
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')

    In this way, the modules are introduced through several sets

    1. Style module (import './assets/css/index.less' / / style Collection)
    @import './atom.less';
    @import './global.less';
    @import './reset.less';
    1. Operation module (import './plugin/index.js' / / import operation set)
    import './custom.js'
    import './ant-design'
    import './tools'
    
    // tools.js
    import Vue from 'vue'
    import moment from 'moment'
    import 'moment/locale/zh-cn'
    import api from '@/request/api'
    import { isInvalid } from '@/utils/verify'
    // Custom components
    moment.locale('zh-cn')
    // Request interface
    Vue.prototype.$api = api
    // Verification tool
    Vue.prototype.$isInvalid = isInvalid
    Vue.prototype.$moment = moment
    
    
    // ant-design.js import on demand
    import Vue from 'vue'
    import {
      Layout,
      Spin,
      Button,
      Icon,
      Avatar,
      Select,
      Drawer,
      Menu,
      Form,
      LocaleProvider,
      Dropdown,
      Divider,
      Modal,
      Input,
      Tooltip,
      notification,
      Popover,
      ConfigProvider,
      Pagination,
      Steps,
      Cascader,
      Row,
      Col
    } from 'ant-design-vue'
    import 'ant-design-vue/dist/antd.less'
    Vue.use(Layout)
    Vue.use(Spin)
    Vue.use(Button)
    Vue.use(Icon)
    Vue.use(Avatar)
    Vue.use(Select)
    Vue.use(Popover)
    Vue.use(Form)
    Vue.use(Drawer)
    Vue.use(Menu)
    Vue.use(LocaleProvider)
    Vue.use(Dropdown)
    Vue.use(Modal)
    Vue.use(Input)
    Vue.use(Divider)
    Vue.use(notification)
    Vue.use(Pagination)
    Vue.use(Tooltip)
    Vue.use(ConfigProvider)
    Vue.use(Steps)
    Vue.use(Cascader)
    Vue.use(Row)
    Vue.use(Col)
    

    4. Axis request secondary encapsulation

    axios, no more introduction, dry goods

    1. New file axios
    2. request interceptor
      Modify the request header and timeout according to your own business requirements
    import axios from 'axios'
    axios.interceptors.request.use(
      config => {
        // Determine whether it is a submission or a regular request
        if (config.data instanceof FormData) {
          config.headers = {
            'Content-Type': 'multipart/form-data' // Format customization here
          }
        } else {
          config.data = JSON.stringify(config.data)
          config.headers = {
            'Content-Type': 'application/json', // Format customization here
            token: getLocalStorage('token')
          }
        }
        config.withCredentials = true
        config.timeout = 5000    // Timeout time
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    1. Response interceptor

    Do some unified processing according to the data returned from the background

    // Add response interceptor
    axios.interceptors.response.use(
      res => {
        let data = res.data
        if (res.statusCode !== 200) {
          if (data.failureReason === 4011 || data.failureReason === 4012) {
            console.log('Need to sign in again')
          }
        } else {
          if (data.resultStates === 0) {
            return data
          } else {
            return Promise.reject(data)
          }
        }
      },
      error => {
        notification['error']({
          message: 'Tips',
          duration: 2,
          description: 'Backstage reporting error'
        })
        // What to do about response errors
        return Promise.reject(error)
      }
    )
    1. Encapsulate get, post, and export
    export function get (url, params = {}) {
      return new Promise((resolve, reject) => {
        axios
          .get(url, {
            params: params
          })
          .then(response => {
            if (response.success) {
              resolve(response.data)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    }
    
    /**
     * Encapsulate post request
     * @param url
     * @param data
     * @returns {Promise}
     */
    export function post (url, data = {}) {
      return new Promise((resolve, reject) => {
        axios.post(url, data).then(
          response => {
            if (response.success) {
              resolve(response.data)
            }
          },
          err => {
            reject(err)
          }
        )
      })
    }
    1. Important: create a new api.js file

    Write all background request interfaces here for unified management

    import { get, post } from './axios'
    const api = {
         reqLogin: p => post('api/user/addFormId', p),
          reqGetInfo: p => post('api/user/addFormId', p)
    }
    export default api
    
    // Introduce api into main.js
    Vue.prototype.$api = api
    
    // Use in this page
    this.$api.reqLogin().then(res => {
          console.log(res)
    })

    Is it very convenient? Clapping, clapping

    A group of young people with dreams https://www.jianshu.com/p/33eee1c26b8a

    Posted by anser316 on Sun, 10 Nov 2019 08:40:09 -0800