How to encapsulate a flexible and highly reusable Vue framework?

Time:2020-9-30

preface:In general, when we create Vue projects, we use the official vue-cli2 scaffold to build projects. Generally speaking, projects created in this mode do not need too much configuration. However, there is a pain point that every project needs to be rebuilt and configured. Is there a way to save these tedious processes? For example, we have two similar ones We use Vue framework, or some projects that we have configured before. We want to use them directly. Today, we will talk about how to build a reusable and flexible framework based on Vue to ensure that we can use it directly when we need to use it.

In general, we need to consider three points:

  1. Management of interface API
  2. Route management
  3. Management of public data
  4. Management of common methods

1、 Management of interface API
First of all, let’s talk about how to manage the interface API in a unified way, which can be convenient and fast when calling, and can reduce HTTP requests, optimize the use experience and save resources.

At present, vue-cli3 has been updated and used for a long time. It is recommended that we use vue-cli3 scaffold to build the project

When we encapsulate Axios requests, we should consider how to manage the API uniformly, which is very important for the optimization level of the project, because the Management API can greatly reduce HTTP requests, save service resources and improve response speed.

For example, we create an API file and create a new one under the API file index.js It is specially used to store the interfaces that need to be used later:

Import request from '@ / request / Axios' // this is our encapsulated Axios file
var ENV =process.env.NODE_ENV
var Tenv;
ENV=='development'?Tenv='/api':Tenv=''
//Interface encapsulation request example
export const getDiaryList = (pageIndex,pageSize) => {
  return request({
    url: Tenv+'/getDiaryList/list',
    method: 'get',
    params: {
        pageIndex:pageIndex,
        pageSize:pageSize,
    }
  })
}

By the way, I’ll post my Axios package code:

/**
 *HTTP configuration
 *Axios parameter description
 */
import axios from 'axios'
Import nprogress from 'nprogress' // this is the animation plug-in of request status in navigation bar, as shown in the figure below
import 'nprogress/nprogress.css'

axios.defaults.timeout = 10000;
//Return to other states
axios.defaults.validateStatus = function (status) {
  Return status > = 200 & & status < = 500; // default
};
//Cross domain request, allow cookie to be saved
axios.defaults.withCredentials = true;
NProgress.configure({
  showSpinner: false
});
//Httprequest interception
axios.interceptors.request.use(config => {
  NProgress.start();
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  //Configure serialize to true in headers to enable serialization
  return config
}, error => {
  return Promise.reject(error)
});
//Httpresponse interception
axios.interceptors.response.use(res => {
  NProgress.done();
  const status = res.data.code || 200;
  const message =  res.data.msg  ||'unknown error';
  if (status !== 200) {
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
});

export default axios;

Nprogress is what we do. Of course, we can’t do it, because this is a background management system
How to encapsulate a flexible and highly reusable Vue framework?
In this way, if we have multiple APIs, we can directly manage them, or we can store multiple types of APIs by file. If we use them, we just need to import them. Because we found that many beginners call them directly in the page every time axios.get In this way

Page import API file:

import {getDiaryList} from '@/api/index'
//It can be more than one object

use:

getDiaryList(pageIndex,pageSize){
    getDiaryList(pageIndex,pageSize).then(res=>{
      //Request successfully processed
      console.log(res.data)
    }).catch(res=>{
      //Request failure processing
      console.log ('request failed ')
    })
},

2、 Route management
Why do you need to manage routing? Routing is the soul of Vue. I took over a project before. All routes are written in the index file under router, and there is no distinction between father and son. It is extremely inconvenient to use and search.
For example, we can create a new folder called pagerouter, We can manage it by modules and pages. For example, we can create a new one under routerpage index.js Management of public, sub module page routing, so that in the use of a lot of convenience, management is also a lot easier, as we next hand over to others when a face at a loss.
Like our routerpage index.js The file can look like this:

/**Routing page profile**/
export default [
    { path: "/", redirect: '/index',},
    {
        path: '/index',
        Name: 'home page',
        component: () => import( '@/views/index'),
        Meta: {requireauth: true}, // check login,
        children:[          
            {
                path:'/',
                Name: 'login page',        
                component: () => import( '@/views/home'),
            },
        ]
    },
    {
        path: '/login',
        Name: 'login page',
        component: () => import( '@/views/login'),
        meta: { requireAuth: false}
    },
]

We’re under router index.js The file can be imported directly, and then add the route. In the above routerpage, the index.js We can configure public, modular and other routing;

import Vue from 'vue'
import VueRouter from 'vue-router'
Import routerpage from '. / routerpage /' // import the routerpage file name I can create,
Vue.use(VueRouter)
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
})
router.addRoutes ([... Routerpage]); // add route
export default router

Another thing I think is that the encapsulation will definitely take into account, and it will certainly be used in the project. It is to check whether the currently opened page users log in and whether they need to log in. It can be controlled according to the global monitoring of routing. A new one can be created in the SRC directory inspect.js Documents are specially managed and controlled

import router from './router'
Import cookies from 'JS cookie' // the plug-in for operating cookies
router.beforeEach((to, from, next) => {
    //Cookies.set('isAuth', 'iii', { expires: 1 });
    // to.matched.some (record =>  record.meta.requireAuth )This is the property of requireauth under the meta that we set in the routing. If it is true, it means that you need to determine whether to log in or not. If it is false, you do not need to judge
    if (to.matched.some(record => record.meta.requireAuth)) {
        if ( Cookies.get ('isauthor ')) {// the criteria for judging can be set by yourself. Here is cookie judgment. Isauth will be stored after logging in
          if (to.fullPath == '/login') {

          } else {
            next()
          }
        } else {
          next({
            path: '/login',
            query: { redirect: to.fullPath } 
          })
        }
   } else {
        Cookies.remove('isAuth');
        next()
   }
})

Then put this file in the main.js Global introduction is enough, and the routing change is to monitor whether the user is logged in or whether the login has expired.
3、 Management of public data
As for the management of public data, the official has provided a perfect method, that is, the management of vuex state data. I have an article specifically said that if you use vuex, you can go and have a look.
How to use vuex
Of course, there is another method, which is the JSON data management method. In this way, you can also manage local public data. But I still recommend using the official vuex.
For example, if we have a navigation system, we need to pre configure the local menu. The reason why I don’t use vuex is that there may be two, three or even four levels of our menu in vuex, or compare the intuitiveness of the data. Then we can do this and create one nav.config.js :

let results={
    Title: 'management platform',
    icon:'el-icon-s-platform',
    tab:[
        {Name: 'navigation 1', path: '/ index / Login','icon ':'el-icon-s-check', children:[
            {Name: 'subset', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 1', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 2', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 3', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 4', path: '/','icon ':'el-icon-s-check'},
        ]},
        {Name: 'navigation 7', path: '/ index / home','icon ':'el-icon-s-check'},
        {Name: 'user management', path: '/ index / Login','icon ':'el icon menu', children:[
            {Name: 'subset 1', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 1', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 2', path: '/','icon ':'el-icon-s-check', children:[
                {Name: 'subset 11', path: '/','icon ':'el-icon-s-check'},
                {Name: 'subset 12', path: '/','icon ':'el-icon-s-check'},
                {Name: 'subset 23', path: '/','icon ':'el-icon-s-check'},
                {Name: 'subset 34', path: '/','icon ':'el-icon-s-check'},
                {Name: 'subset 45', path: '/','icon ':'el-icon-s-check'},
            ]},
            {Name: 'subset 3', path: '/','icon ':'el-icon-s-check'},
            {Name: 'subset 4', path: '/','icon ':'el-icon-s-check'},
        ]},
        {Name: 'navigation 9', path: '/ index / Login','icon ':'el-icon-s-check'},
        {Name: 'navigation 10', path: '/ index / Login','icon ':'el-icon-s-check'}
    ]
}
export default {
  results
}

Then, import or assign the required file to the state of vuex:

import navConfig from'../nav.config'
data(){
    return {
        tabResults:navConfig.results,
    }
},

In this way, we can directly use it in specific files this.tabResults It is also very convenient to operate or bind the page directly. It is mostly used for local menu configuration and can be flexibly managed
How to encapsulate a flexible and highly reusable Vue framework?

4、 Management of common methods
In fact, the management of public methods is similar to the management of public data, and vuex can also be implemented. However, we are generally used to managing public method files to achieve intuitive, convenient and flexible effects.
For example, we can build a new one utils.js :

/**
 *Date formatting
 */
export function dateFormat(date, format) {
  format = format || 'yyyy-MM-dd hh:mm:ss';
  if (date !== 'Invalid Date') {
    let o = {
      "M+": date.getMonth() + 1, //month
      "d+": date.getDate(), //day
      "h+": date.getHours(), //hour
      "m+": date.getMinutes(), //minute
      "s+": date.getSeconds(), //second
      "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
      "S": date.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
      if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
          RegExp.$1.length === 1 ? o[k] :
            ("00" + o[k]).substr(("" + o[k]).length));
    return format;
  }
  return '';
}
/**
 *Strong conversion from JSON to form type
 * @param obj
 * @returns {FormData}
 */
export function toFormData(obj) {
  const data = new FormData();
  Object.keys(obj).forEach(key => {
    data.append(key, Array.isArray(obj[key]) ? obj[key].join(',') : obj[key]);
  });
  return data;
}

Can be in main.js Introduce separately or completely
Introduce them separately, using only one or more methods:

import { toFormData } from './utils'

All introduced:

import Utils from './utils'
//Use
Utils.toFormData(obj)

Summary:The above is how to package our own reusable Vue framework from four aspects. The recommended method is to package and save one, which can be put on alicode or GitHub. In this way, we can do basic proxy or domain name configuration directly from dowm next time, which can greatly save a lot of time and avoid duplication Work.
Well, I’m bulangxiong, welcome to pay attention to my blog app (currently in the process of improvement), we exchange education together, progress and growth together.
Applet code:
How to encapsulate a flexible and highly reusable Vue framework?
Or we have searched the app “Zhifu blog” on wechat
Zhifu blog official website

Recommended Today

Comparison and analysis of Py = > redis and python operation redis syntax

preface R: For redis cli P: Redis for Python get ready pip install redis pool = redis.ConnectionPool(host=’39.107.86.223′, port=6379, db=1) redis = redis.Redis(connection_pool=pool) Redis. All commands I have omitted all the following commands. If there are conflicts with Python built-in functions, I will add redis Global command Dbsize (number of returned keys) R: dbsize P: print(redis.dbsize()) […]