26-uni.request请求网络接口

404 阅读3分钟

文档在uniapp官网--API--网络模块

uni.request(OBJECT)

在vue中用axios或者ajax,在这uni中用request

代码逻辑:每次加载页面,onLoad方法就会执行一次,里面的获取图片路径的方法就会被自动调用,然后将获取到的接口图片变量赋值给data中的变量,最后image标签拿到这个变量的值,也就是这个图片渲染到页面中


<template>
  <view>
    <image :src="picurl" mode="aspectFill"></image>
  </view>
</template>

<script>
  export default { 
    data() {
      return {
        picurl:''
      };
    },
    methods:{
      getPicUrl(){
        uni.request({
          url:"https://dog.ceo/api/breeds/image/random",
          success:res=>{
            this.picurl =  res.data.message
          }
        })
      } 
    },
    onLoad() {
      this.getPicUrl()
    }
  }
</script>

<style lang="scss">

</style>

成功,每次刷新页面都会展示不同的狗图片 image.png

给图片标签绑定一个点击事件,事件名就是获取接口的函数名,这样,每次点击图片就能重新获取一次接口,重新下载一张图片了

<template>
  <view>
    <image :src="picurl" mode="aspectFill" @click="getPicUrl"></image>
  </view>
</template>

如果接口获取数据慢,就在网络请求方法之前写一个showloading,获取到数据后,隐藏loading(获取到了数据,代表箭头函数条件成功执行,在箭头函数里写隐藏loading就行了)

<template>
  <view>
    <image :src="picurl" mode="aspectFill" @click="getPicUrl"></image>
  </view>
</template>

<script>
  export default { 
    data() {
      return {
        picurl:''
      };
    },
    methods:{
      getPicUrl(){
        uni.showLoading({
          title:"数据加载中..."
        })
        uni.request({
          url:"https://dog.ceo/api/breeds/image/random",
          success:res=>{
            this.picurl =  res.data.message,
            uni.hideLoading()
          }
        })
      } 
    },
    onLoad() {
      this.getPicUrl()
    }
  }
</script>

<style lang="scss">

</style>

image.png

timeOut 设置请求时间

如果长时间请求不到资源,就会一直卡住,需要设置这个配置项,如果长时间请求不到资源,就断开请求

<template>
  <view>
    <image :src="picurl" mode="aspectFill" @click="getPicUrl"></image>
  </view>
</template>

<script>
  export default { 
    data() {
      return {
        picurl:''
      };
    },
    methods:{
      getPicUrl(){
        uni.showLoading({
          title:"数据加载中..."
        });
        uni.request({
          url:"https://dog.ceo/api/breeds/image/random",
          timeout:1500,
          success:res=>{
            this.picurl =  res.data.message
            // uni.hideLoading()
          },
          fail:err=>{
            
          },
          complete:()=>{
            // 无论接口调用成功失败都执行这个回调函数--隐藏掉刷新弹窗
            uni.hideLoading()
          },
        });
      } 
    },
    onLoad() {
      this.getPicUrl()
    }
  }
</script>

<style lang="scss">

</style>

带参数的网络请求

换接口要打印一下,每个接口的结构是不一样的

uni.request({
          url:"https://api.thecatapi.com/v1/images/search?limit=1",
          timeout:1500,
          success:res=>{
            console.log(res);
}, 

成功请求到数据并且打印了返回值

image.png

狗子接口的结构是一个字符串,而猫咪接口是一个数组,在data中定义变量就要改成一个数组,将获取到的接口返回值赋给这个变量,才能在template结构中使用

在页面中也不能直接绑定使用,而是要循环遍历列表中的值,放到标签里,for循环要带key,接口里本身也有id这一项,就用接口自带的id作为key

注意:vue2的模板结构最外层最好是一个空的view根标签

<template>
 <view class="">
   <view v-for="item in picurl" :key="item.id">
     <image :src="item.url" mode="aspectFill" @click="getPicUrl"></image>
   </view>
 </view>
</template>

<script>
  export default { 
    data() {
      return {
        picurl:[]
      };
    },
    methods:{
      getPicUrl(){
        uni.showLoading({
          title:"数据加载中..."
        });
        uni.request({
          url:"https://api.thecatapi.com/v1/images/search?limit=1",
          timeout:1500,
          success:res=>{
            this.picurl = res.data
          },
          fail:err=>{
            
          },
          complete:()=>{
            // 无论接口调用成功失败都执行这个回调函数--隐藏掉刷新弹窗
            uni.hideLoading()
          },
        });
      } 
    },
    onLoad() {
      this.getPicUrl()
    }
  }
</script>

<style lang="scss">

</style>

成功获取到了图片,同时,点击图片,会自动刷新一张新图片 image.png

url携带参数的写法

data属性是request自带的属性值,用来写url后面携带的参数,用法:

不要问号,携带的参数以对象的形式写到data配置项中,这里data中的limit是接口本身自带的

原本的接口写法 api.thecatapi.com/v1/images/s…

使用data携带参数的写法

uni.request({
          url:"https://api.thecatapi.com/v1/images/search",
          data:{
            limit: 2
          }
          timeout:1500,
          success:res=>{
            this.picurl = res.data
          },
          fail:err=>{
            
          },
          complete:()=>{
            // 无论接口调用成功失败都执行这个回调函数--隐藏掉刷新弹窗
            uni.hideLoading()
          },
});

methods 设置请求的方法

下面这个接口不支持post请求,所以这里用get测试,他的post请求url仅允许写到posts

uni.request({
          url:"https://jsonplaceholder.typicode.com/posts/1",
          timeout:1500,
          success:res=>{
            console.log(res);
          },
          method:'GET',
          fail:err=>{
            
          },
          complete:()=>{
            // 无论接口调用成功失败都执行这个回调函数--隐藏掉刷新弹窗
            uni.hideLoading()
          },
});

免费测试API接口

jsonplaceholder.typicode.com/posts

这是一个外国的测试接口网站,GET、POST都可以测试

通过这个接口做一个小案例,将获取到的数据渲染到页面

代码逻辑:

在methods中写请求方法,在onload中调用,之所以在这里调用,是因为页面一被加载,这个生命周期函数就会自动执行,把网络请求方法在这里调用,只要一刷新页面,就会自动执行网络请求函数,然后把获取到的值赋值给在data中自定义的变量,模板中拿到的就是data中的数据,最后在标签里用for循环将拿到的数据渲染到页面,for循环一定要带key

<template>
 <view class="out">
   <view class="row" v-for="item in listArr" :key="item.id">
    <view class="title">{{item.title}}</view>
    <view class="content">{{item.body}}</view>
   </view>
 </view>
</template>

<script>
  export default { 
    data() {
      return {
        listArr:[]
      };
    },
    methods:{
      getData(){
        uni.request({
          url:"https://jsonplaceholder.typicode.com/posts",
          success:res=>{
            this.listArr = res.data
          }
        })
      }
    },
    onLoad() {
      // 在这里调用,上面写的请求函数才会被执行
      this.getData()
    }
  }
</script>

<style lang="scss">
.out {
  padding: 50rpx 30rpx;
  .row {
    padding: 20rpx 0;
    border-bottom: 1px dotted #000;
    .title {
      font-size: 36rpx;
      padding-bottom: 15rpx;
      color: #333;
    }
    .content {
      font-size: 28rpx;
      color: #888;
    }
  }
}
</style>

效果: image.png

新建一个页面detail,实现点击标题进入详情页

绑定点击事件进行页面跳转

<template>
 <view class="out">
   <view class="row" v-for="item in listArr" :key="item.id" @click="clickItem">
    <view class="title">{{item.title}}</view>
    <view class="content">{{item.body}}</view>
   </view>
 </view>
</template>

<script>
  export default { 
    data() {
      return {
        listArr:[]
      };
    },
    methods:{
      // 请求网络数据
      getData(){
        uni.request({
          url:"https://jsonplaceholder.typicode.com/posts",
          success:res=>{
            this.listArr = res.data
          }
        })
      },
      // 点击标题跳转到详情页
      clickItem(){
        uni.navigateTo({
          url:"/pages/detail/detail"
        })
      }
    },
    onLoad() {
      // 在这里调用,上面写的请求函数才会被执行
      this.getData()
    }
  }
</script>

<style lang="scss">
.out {
  padding: 50rpx 30rpx;
  .row {
    padding: 20rpx 0;
    border-bottom: 1px dotted #000;
    .title {
      font-size: 36rpx;
      padding-bottom: 15rpx;
      color: #333;
    }
    .content {
      font-size: 28rpx;
      color: #888;
    }
  }
}
</style>

前面写的详情部分全展示出来了,截取一部分出来,剩下的展示到详情页