uni-request请求页面渲染

175 阅读1分钟

前端最主要的还是将数据从后端请求过来,对数据进行处理,并且渲染在界面, 前面讲到了uni-app请求接口跨域问题www.jianshu.com/p/aea58ee40…~

今天主要写一下关于uni.request请求相关操作 文档:uniapp.dcloud.io/api/request…

首先准备服务器接口数据:www.intmote.com/test.json 目的是把这些数据拿过来渲染在前端界面上

具体步骤 1:首先要写一个空白的组件页面

<template>
    <view>     
        空白页面请求数据示例
    </view>
</template>
<script>
    export default {
        data() {
            return {}
               },
        onLoad() {},
        methods: {}
    }
</script>
<style>
</style>

2:看文档,写请求方法 uniapp.dcloud.io/api/request… 使用示例代码,复制黏贴过来 在这里插入图片描述 将代码写在getList()函数里面,并且把函数 写在methods的方法里面 这里需要将 url:"www.example.com/request",改成 url: "/api/test.json", (前面已经设置了跨域的代理了)

 methods: {  
            getList() {
            uni.request({
              url: '/api/test.json', 
                success: (res) => {
                    console.log(res.data);
                    this.text = 'request success';
                }
            });
            }
        }

3:载入页面的时候加载调用请求函数请求api

 onLoad() {
             this.getList();
},

4:成功调用,在控制台打印 console.log(res.data); 在这里插入图片描述 5:在data里面写一个空数组itemList: [ ],接收api里面返回的数据

data() {
            return {  
                 itemList: []
            }
        },

6:api请求成功之后,将请求过来的数据赋值给上一步在data()定义的数组itemList 里面

 success: (res) => {
                        console.log(res.data);
                         this.itemList =res.data.first;
                    }

7:赋值完成之后,需要对数据进行循环处理,渲染在view标签里面

<view class="uni-padding-wrap uni-common-mt" v-for="item in itemList">
             <span>{{item.name}}</span>
             <span>{{item.nick}}</span>
        </view>

ok,完成了,效果如下在这里插入图片描述 参考代码

<template>
    <view>     
        <view class="uni-padding-wrap uni-common-mt" v-for="item in itemList">
             <span>{{item.name}}</span>
             <span>{{item.nick}}</span>
        </view>
    </view>
</template>
<script>
    export default {
        data() {
            return {  
                 itemList: []
            }
        },
        onLoad() {
                   this.getList();
               },
        methods: {
             getList() {
                uni.request({
                    url: '/api/test.json', 
                    success: (res) => {
                        console.log(res.data);
                         this.itemList =res.data.first;
                    }
                });
            }
        }
    }
</script>
<style>
.img {
    width: 500upx;
    height: 500upx;
    margin: 0 95upx;
}
</style>