vue封装请求、合并js、合并多个js
作为一个后端开发,写前端时发现,每次导入api接口都会有一堆代码,像下面这样:
import {footprintList, footprintDelete} from '@/api/userApi.js'
import {addressList} from '@/api/userApi.js'
import {getSku} from '@/api/goodsApi.js'// .. 调用方法
要核对名称等一些列操作,我就很苦恼,为什么不能一个次导入,随意调用?(一次编译,到处运行)
参考网上,实现一次导入,任意模块调用。实现了下面的方案:
转自:https://lingkang.top/archives/he-bing-duo-ge-js
转自:https://lingkang.top/archives/he-bing-duo-ge-js
转自:https://lingkang.top/archives/he-bing-duo-ge-js
1、编写一个公用的js --> allApi.js
allApi.js
import * as userApi from './userApi.js'
import * as goodsApi from './goodsApi.js'
import * as cartApi from './cartApi.js'
import * as collectionApi from './collectionApi.js'
import * as footprintApi from './footprintApi.js'export default {userApi,goodsApi,cartApi,collectionApi,footprintApi,
}
例如footprintApi.js
中的内容
import request from './request.js'// 浏览足迹------------------------------------
export function footprintAdd(id) {return request.post(("/api/user/footprint/add"), {id})
}export function footprintList(param) {return request.get('/api/user/footprint/list', {params: param})
}export function footprintDelete(id) {return request.post('/api/user/footprint/delete', {id})
}
2、调用聚合js中的方法
通过调用 allApi.模块API
.模块的方法
实现接口聚合
<script setup>
import allApi from '@/api/allApi.js'// ....
const onDel = () => {let ids = []selectedList.value.forEach(e => ids.push(e.id))// 调用allApi.cartApi.deleteCart(ids).then(res => {showToast('操作成功')loadData()})
}// ..
const loadData = () => {allApi.collectionApi.collectionList(param.value).then(res => {list.value = list.value.concat(res.data)// 数据全部加载完成if (list.value.length >= res.total) {finished.value = true;}}).finally(() => {loading.value = false;})
}</script>
项目截图