uniapp项目中使用第三方的包@escook/request-miniprogram来创建网络请求

1.安装

npm install @escook/request-miniprogram

2.在main.js中导入

import App from './App'
import Vue from 'vue'

// 导入网络请求的包
import { $http } from '@escook/request-miniprogram'

// 在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用
uni.$http = $http

// 配置请求根路径
$http.baseUrl = `https://www.uinav.com`

// 请求拦截器
$http.beforeRequest = function(options){
  uni.showLoading({
    title:'数据加载中...'
  })
}

// 响应拦截器
$http.afterRequest = function(){
  uni.hideLoading()
}

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})
app.$mount()

 3.在页面中使用,以请求首页轮播图数据为例,项目pages/home/home.vue代码如下:

<template>
  <view>
    <!-- 轮播图代码区域 -->
    <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
      <swiper-item v-for="item,index in swiperList" :key="index">
        <view class="swiper-item">
          <image :src="item.image_src"></image>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        swiperList: []
      };
    },
    onLoad() {
      this.getSwiperList()
    },
    methods: {
      async getSwiperList(){
        const {data} = await uni.$http.get('/api/public/v1/home/swiperdata')
        if(data.meta.status !== 200){
          return uni.showToast({
            title: '数据请求失败',
            duration: 1500,
            icon:'none'
          })
        }
        this.swiperList = data.message
      }
    }
  }
</script>

<style lang="scss">
swiper{
  width:750rpx;
  .swiper-item,
  image{
    width:100%;
    height:100%;
  }
}
</style>

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值