uniapp 配置网络请求并使用请求轮播图

由于平台的限制,小程序项目中不支持 axios,而且原生的 wx.request() API 功能较为简单,不支持拦截器等全局定制的功能。因此,建议在 uni-app 项目中****使用 @escook/request-miniprogram 第三方包发起网络数据请求。

官方文档:@escook/request-miniprogram - npm (npmjs.com)

1、安装 相应的包

javascript 复制代码
1、安装一个npm包管理文件:
npm init -y

2、安装我们这个网络请求第三方工具
npm i @escook/request-miniprogram

2、导入 $http 对象

javascript 复制代码
import { $http } from '@escook/request-miniprogram'

uni.$http = $http

3、配置 请求根路径、请求拦截器

javascript 复制代码
// 2、配置请求根路径
$http.baseUrl = 'https://api-hmugo-web.itheima.net'

// 3、请求开始之前做一些事情
$http.beforeRequest = function (options) {
  uni.showLoading({
    title: '数据加载中...',
  })
}

// 4、请求完成之后做一些事情
$http.afterRequest = function () {
  uni.hideLoading()
}

4、使用 网络请求

先在pages下建立需要的文件夹,再在这些文件夹上右键点击新建页面,创建就行

html 复制代码
<template>
  <view>
    <!-- 轮播图区域 -->
    <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
      <!-- 循环渲染轮播图的 item 项 -->
      <swiper-item v-for="(item, i) in swiperList" :key="i">
        <view class="swiper-item">
          <!-- 动态绑定图片的 src 属性 -->
          <image :src="item.image_src"></image>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 1. 轮播图的数据列表,默认为空数组
        swiperList: [],
      }
    },
    onLoad() {
      // 2. 在小程序页面刚加载的时候,调用获取轮播图数据的方法
      this.getSwiperList()
    },
    methods: {
      // 3. 获取轮播图数据的方法
      async getSwiperList() {
        // 3.1 发起请求 【把data从res{data}中解构出来】
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/home/swiperdata')
        console.log(res);
        // 3.2 请求失败
        if (res.meta.status !== 200) {
          return uni.showToast({
            title: '数据请求失败!',
            duration: 1500,
            icon: 'none',
          })
        }
        // 3.3 请求成功,为 data 中的数据赋值
        this.swiperList = res.message
      },
    },
  }
</script>

<style lang="scss">
  swiper {
    height: 330rpx;

    .swiper-item,
    image {
      width: 100%;
      height: 100%;
    }
  }
</style>
相关推荐
CHB10 小时前
HDC2026 演讲实录|AI 驱动的跨端进化:利用 uni-agent 快速构建高性能鸿蒙应用
uni-app·harmonyos
2501_9159184117 小时前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview
玩烂小程序17 小时前
微信小程序手串DIY功能开发实录:飞入动画 + 环形排布 + 拖拽换序 + 旋转查看 + 保存设计
微信小程序
斯内普吖18 小时前
(开源)高校素拓分管理系统小程序实战指南 基于 Java + SpringBoot + uni-app + Vue + MySQL
java·spring boot·mysql·小程序·uni-app·开源
何时梦醒19 小时前
HTML5 Canvas 从入门到实战:手把手教你打造一款"打飞机"小游戏
微信小程序
海阔天空668819 小时前
uniapp开启调试模式
uni-app·uniapp开启调试模式
master33619 小时前
SSL 证书链问题导致微信小程序无法正常工作
网络协议·微信小程序·ssl
小葛要努力20 小时前
安装nvm 管理node.js版本实现vue2和vue3项目共存
node.js·vue·nvm
这里是杨杨吖1 天前
SpringBoot+Vue高校在线考试系统 附带详细运行指导视频
vue·在线考试·springboot
anyup2 天前
分享 5 套 uni-app 实用主题,一键适配暗黑模式
前端·uni-app·视觉设计