Vue项目接口管理-Vue模块自动装配

知识点:依赖管理

文档地址:https://webpack.docschina.org/guides/dependency-management/

项目目录结构:

 

/api/index.js 源码
// require.context 获取 指定目录下匹配文件
const ctx = require.context('./service/', true, /.js/)
const modules = {}

ctx.keys().forEach( key => {
    // 文件名去掉后缀及首字母小写处理
    let name = key.replace(/(^./|.js$)/g, '');
    name = name.substr(0, 1).toLowerCase() + name.substr(1);
    modules[name] = ctx(key).default;
});
export default modules; 

入口文件main.js 加入

// 注册接口服务
import api from './api/index.js';
Vue.prototype.$api = global.api;

 在页面/组件中调用

this.$api.appService.initial().then(res => {
    this.version = res.version;
});

 其中 /api/service/AppService.js源码

import Http from '../http/http.js';

/**
 * APP通用接口
 */

export default {
    
    /**
     * 获取初始化信息
     */
    initial() {
        return Http.get('/initial');
    }
    
}
原文地址:https://www.cnblogs.com/rubekid/p/15087157.html