项目中会碰到要全局注入多个js文件
上面的js 都是一些接口文件,每个页面important 比较麻烦 就采用全局注入
这种方法显然不叫繁琐,一旦js 比较多代码就显得比较臃肿,所以采用了 vue 自带的 require.context的方法,要读取的js文件 必须放在api文件中
//读取api路径下的js接口文件
const apiFiles = require.context('./data/remote/api', true, /\.js$/)
const api = apiFiles.keys().reduce((api, modulePath) => {
// set './app.js' => 'app'
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = apiFiles(modulePath)
api[moduleName] = value.default
return api
}, {})
Vue.prototype.api = api;
使用
this.api.文件名.方法()