01. Axios encapsulation

(1) Introduce Axios

import axios from 'axios'
Copy the code

(2) Create an instance

const request = axios.create({
    / / configuration items
})
Copy the code

(a) Regarding configuration items:

  • BaseURL: Request address prefix, automatically added to the front of the URL

    • Generally, there is a difference between a development environment and a production environmentbaseURL
    • Therefore, you need to switch different ones for different environmentsbseURL
    baseURL: process.env.NODE_ENV === 'production' ? '/production' : '/development'
    Copy the code
  • Timeout: Specifies the default timeout period for a request, expressed in milliseconds. If this timeout period is exceeded, the request will fail

    timeout: 10000
    Copy the code

(3) Request interception

  • Before sending the request, the request is intercepted, where some processing of the data is done
    • It is used to add a Token to the request header to determine the login status
// Request interceptor request
request.interceptors.request.use(    
    config= > {
        // Do some processing after interception. For example, check whether there is a token
        const token = localStorage.getItem('token')
        if(token){
            // If there is a token, add the token to the request header
            config.headers['X-Token'] = token
        }
        // You must return to config after processing
        return config
    },    
    error= > {
        return Promise.reject(error)
    })
}
Copy the code

(4) Response interception

  • Intercept the data returned to us by the server, and make some processing judgments on the data before obtaining it
    • It is used to uniformly process errors
// Response interceptor response
request.interceptors.response.use(
    // The request succeeded
    response= > {
        if (response.status === 200) {  
            // If the returned status code is 200, the interface request succeeds and data can be obtained normally
            return Promise.resolve(response);        
        } else {  
            // Otherwise, an error is thrown
            return Promise.reject(response); }},// The request failed
    error= > {
        // Operate on other returned errors. Such as 401, 403, 404, etc
        return Promise.reject(error)
    }
)
Copy the code

(5) Request

  • Can begetandpostRequest encapsulation, but I personally like to write it this way
// api.js
import request from '@/utils/request'

export default getList(params){
    return request({
        url: '/'.method: 'get',
        params
    })
}

export default postList(data){
    return request({
        url: '/'.method: 'post',
        data
    })
}
Copy the code

(6) Use

  • Import API files directly for use, either globally or on demand
import { getList, postList } from '@/api/api.js'

getList(params).then(res= > {
    // ...
}).catch(error= > {
    // ...
})
Copy the code

(7)

// request.js
import axios from 'axios'

const request = axios.create({
    baseURL: process.env.NODE_ENV === 'production' ? ` / ` : '/apis'.// Configure the base address
    headers: {
        get: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        },
        post: {
            'Content-Type': 'application/json; charset=utf-8'}},timeout: 30000.// Configure the timeout period
})

// Request interceptor
request.interceptors.request.use(
    config= > {
        return config
    }, 
    error= > {
        // Error thrown to business code
        error.data = {}
        error.data.msg = 'Server exception, please contact administrator! '
        return Promise.resolve(error)
    }
)

// Response interceptor
request.interceptors.response.use(
    // The request succeeded
    response= > {
        const status = response.status // Get the status code
        let msg = ' '
        if (status < 200 || status >= 300) {
            // Handle HTTP errors and throw into the business code
            msg = showStatus(status)
            if (typeof response.data === 'string') {
                response.data = { msg }
            } else {
                response.data.msg = msg
            }
        }
        return response
    }, 
    / / request
    error= > {
        console.log('err' + error)
        Message({
            message: error.message,
            type: 'error'.duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

const showStatus = status= > {
    let message = ' '
    switch (status) {
        case 400:
            message = '400: Request error '
            break
        case 401:
            message = '401: Unauthorized, please log in again '
            break
        case 403:
            message = '403: Access denied '
            break
        case 404:
            message = '404: Requested resource not found '
            break
        case 405:
            message = '405: Request method not allowed '
        case 408:
            message = '408:: Request timed out '
            break
        case 500:
            message = '500: Internal server error '
            break
        case 501:
            message = '501: Service not realized '
            break
        case 502:
            message = '502: Network error '
            break
        case 503:
            message = '503: Service unavailable '
            break
        case 504:
            message = '504: Network Timeout '
            break
        case 505:
            message = 'HTTP version not supported (505)'
            break
        default:
            message = 'connection error, error code :(${status})! `
    }
    return `${message}Please check the network or contact the administrator! `
}

export default request

Copy the code

02. How do I reset data in Vue?

  • Use: Object.assign(newObj, oldObj)

    • this.$data: getThe current stateThe data under the
    • this.$options.data(): Gets the componentThe initial stateThe data under the
    Object.assign(this.$data, this.$options.data())
    
    // If only one property is reset
    this.id = this.$options.data().id;
    Copy the code

03. Why is data a function?

  • Due to the nature of JavaScript, data must exist as a function in a component, not as an object

    • Defined as a function return value, a new copy of data is returned each time a component is reused
    • Defined as objects, all component instances will share a single data, because objects are reference types
  • Therefore, to ensure that data does not conflict between different instances of the component, data must be a function

04. What is the function of vue-loader?

  • Function: a Webpack-based loader that can parse and convert. Vue files

    • Extract the template, script, and style tags and transfer them to the corresponding loader to convert them into JS modules

05. What is the function of keep-alive?

  • keep-aliveVue is a built-in component that enables the inclusion of componentsPreserve state and cache to avoid re-rendering

06. What is vue.use?

  • Vue. use is used to work with plug-ins, where we can extend global components, directives, prototype methods, and so on

  • Vue.js plug-ins should expose an install method. The first argument to this method is the Vue constructor, and the second argument is an optional option object for the configuration passed in to the plug-in

    MyPlugin.install = function (Vue, options) {
        // 1. Add a global method or attribute
        Vue.myGlobalMethod = function () {
            / / logic...
        }
        // 2. Add global resources
        Vue.directive('my-directive', {
            bind (el, binding, vnode, oldVnode) {
                / / logic...}... })// 3. Inject component options
        Vue.mixin({
            created: function () {
                / / logic...}... })// 4. Add instance methods
        Vue.prototype.$myMethod = function (methodOptions) {
            / / logic...
        }
        // 5. Register global components
        Vue.component('myButton', {/ /... Component options})}// --------------
    Vue.use(MyPlugin, {
        / / parameters
    })
    
    Copy the code

    When vue.use () is used, the install method inside the plug-in is called

    • If the plug-in passes in an object, it executes itinstallmethods
    • If it is a function, it executes itself andbind thisfornull, and pass in additional parameters

07. How do I mount a property/method on a Vue instance?

  • useVue.prototype.$xxAdd a property/method to the prototype of Vue so that it can be read on any instance

08. What are the advantages and disadvantages of SPA single page?

  • Concept: SPA issingle-page applicationThe corresponding HTML, JavaScript, and CSS are loaded only when the page is initialized
    • Once the page is loaded, SPA will not reload or jump the page due to the user’s operation
    • Instead, routing mechanisms are used to transform HTML content, interact with the user and avoid page reloading
  • Advantages:
    • 1) Good user experience, fast, content change does not need to reload the whole page, avoid unnecessary jump and repeated rendering
    • 2) SPA has less pressure than server
    • 3) The responsibilities of the front and back ends are separated, and the architecture is clear. The front end carries out interactive logic, and the back end is responsible for data processing
  • Disadvantages:
    • 1) Slow loading of the first screen (initial) : In order to achieve the function and display effect of a single page Web application, JavaScript and CSS need to be loaded uniformly when the page is loaded, and some pages need to be loaded as required
    • 2) Bad for SEO: Because all content is displayed dynamically on a page, it has a natural disadvantage in SEO

I front-end side dish chicken, if there is wrong, please forgive