vue封装请求、合并js、合并多个js

本文介绍了如何在Vue项目中通过将多个API文件导入并整合到一个allApi.js文件,实现代码复用和模块化管理,提高了前端开发效率。开发者可以方便地调用聚合后的接口,简化了导入和调用过程。
摘要由CSDN通过智能技术生成

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>

项目截图

在这里插入图片描述
在这里插入图片描述

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌康ACG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值