Design Technical points

  • vue3
  • Shall not apply to the ts
  • Configuration vant3
  • Mobile adaptation

Create a VUE3 project

vue create vue3-project
Copy the code

Partial Step Description

Select a creation method

  • The default vuE2 version
  • Vue3 is the default version
  • Manual configuration

Let’s pick the third option here

Select the characteristic attributes required by the project

  • Select the VUE version
  • Babel is used to handle compatibility
  • We don’t use TS here
  • PWA(Progressive Web App) related links

Add vant3.0 style

Vant3.0 document address

# Vue 3 project, install Vant 3: NPM I vant@next -sCopy the code

Rem adaptation on mobile terminal

Vant officials also provided us with a solution

Postcss – PxtoREM is a postCSS plugin for converting units to REM lib-flexible for setting REM reference values

Postcss configuration

Create postcss.config.js in the project root directory

module.exports = {
    "plugins": {
        "autoprefixer": {
            // Configure to use autoprefixer
            overrideBrowserslist: ["last 15 versions"].browsers: ["Android > = 4.0"."iOS >= 7"]},"postcss-pxtorem": {
            rootValue: 100.Vant's official root font size is 37.5
            propList: [The '*'].selectorBlackList: ['.norem'] // filter out. Norem - classes that start with norem conversion}}}Copy the code

Note: rootValue is set to 100 to facilitate the conversion of sizes in the UI diagram, where 1rem=100px

SRC folder utils folder utils folder rem.js folder

// REM equal match configuration file
// Base size
const baseSize = 100
// Note that this value must be consistent with rootValue in the postcss.config.js file
// Set the rem function
function setRem() {
    // The current page width relative to the 375 width scale can be modified according to your own needs, generally the design is 750 wide.
    const scale = document.documentElement.clientWidth / 375
    // Set the font size of the root node of the page (" math.min (scale, 2) "means the maximum zoom ratio is 2, which can be adjusted according to actual business requirements)
    document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
/ / initialization
setRem()
// Resets rem when changing the window size
window.onresize = function () {
    console.log("I did it.")
    setRem()
}
Copy the code

Rem.js is used in main.js

import './utils/rem'
Copy the code

Note The base size in rem.js must be the same as the rootValue value set in postcss.config.js. Rem.js is mainly used for equal proportion configuration files

Axio secondary encapsulation

Create http.js in utils

// src/utils/http.js

import axios from 'axios';

const getBaseUrl = (env) = > {
    let base = {
        production: '/'.development: 'https://www.baidu.com'.test: 'http://localhost:3001',
    }[env];
    if(! base) { base ='/';
    }
    return base;
};

class NewAxios {
    constructor() {
        this.baseURL = getBaseUrl(process.env.NODE_ENV);
        this.timeout = 10000;
        this.withCredentials = true;
    }

    setInterceptors = (instance, url) = > {
        instance.interceptors.request.use((config) = > {
            // Add loading here
            / / configuration token
            config.headers.AuthorizationToken = localStorage.getItem('AuthorizationToken') | |' ';
            return config;
        }, err= > Promise.reject(err));

        instance.interceptors.response.use((response) = > {
            // Remove loading here
            // ToDO: Where you want to pre-process the response results based on business needs
            return response;
        }, (err) = > {
            if (err.response) { // Response error code processing
                switch (err.response.status) {
                    case '403':
                        // todo: handler server forbidden error
                        break;
                    // todo: handler other status code
                    default:
                        break;
                }
                return Promise.reject(err.response);
            }
            if (!window.navigator.online) { // The network is disconnected
                // todo: jump to offline page
                return -1;
            }
            return Promise.reject(err);
        });
    }

    request(options) {
        // Each request creates a new axios instance.
        const instance = axios.create();
        const config = { // Merge the parameters passed by the user with the common configuration.. options,baseURL: this.baseURL,
            timeout: this.timeout,
            withCredentials: this.withCredentials,
        };
        // Configure interceptors. Support different interceptors based on different URLS.
        this.setInterceptors(instance, options.url);
        return instance(config); // Returns the execution result of the AXIos instance}}export default new NewAxios();

Copy the code

SRC folder to create API, API 1: index.js 2:home.js

//index.js
export * from './home';


//home.js
import axios from '@/utils/http';
export const fetchData = data= > axios.request({
  method:'get'.url: '/123/data'.params:data
});
export default {};
Copy the code

Note: This encapsulation method creates one new instance per request, whether too many instances affect package size or other issues is up for debate

Class encapsulation is used here for the following reasons:

In the Request method, create a new AXIos instance, receive the request configuration parameters, process the parameters, add the configuration, and return the result of the request (a Promise object) for the AXIos instance. You can also use the default exported AXIOS instance without creating it and put all the configuration on it, but then the entire project will share one AxiOS instance. While this is fine for most projects, some projects may have completely different request and response structures for different service addresses, which may not be supported by sharing a single instance. So to make encapsulation more generic and flexible, I use axios’s create method so that each request is a new AXIOS instance.

Refer to the article