简介

前端通过request向后端数据库请求数据,通过get获取到后端数据库数据。打印到console()上。获取到数据后,再渲染到页面,数据库中的数据就渲染到页面上了。

具体步骤

1,先写一个button按钮

@click一个点击事件

2,写get请求

写请求方法,文档:https://uniapp.dcloud.io/api/request/request
找到示例代码

uni.request({
    url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' //自定义请求头信息
    },
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});

3,后端写好api接口程序

HTTP响应程序,准备服务器接口:http://8.136.186.93:5001/device/device1data
数据库包含好程序

4,把数据打印到工作台上

数据请求成功后,打印到工作台上

success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }

初步代码

<template>
	<button @click="getlist">按键</button>
</template>

<script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {

		},
		methods: {
			getlist(){
				uni.request({
				    url: 'http://8.136.186.93:5001/device/device1data', //仅为示例,并非真实接口地址。
				    data: {
				        text: 'uni.request'
				    },
				    header: {
				        'custom-header': 'hello' //自定义请求头信息
				    },
				    success: (res) => {
				        console.log(res.data);
				        this.text = 'request success';
				    }
				});
			}
            
		}
	}
</script>
<style>
</style>

点击按钮,控制台显示信息

在这里插入图片描述

数据请求+页面渲染

1,加载调用请求函数请求api

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

2,在data里面写一个空数组itemList: [],接收api里面返回的数据

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

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

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

4,写 view界面,对数据进行循环遍历,渲染在view界面上。

itemList获得从后台request的数据。inclination,weight是数据库中数据的表头。

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

ok,完成

参考程序

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

<script>
	export default {
		data() {
			return {
               itemList: []
			}
		},
		onLoad() {

             this.getList();
		},
		methods: {
         getList() {
            uni.request({
                 url: 'http://8.136.186.93:5001/device/device1data',
                 success: (res) => {
                    console.log(res.data);
                          this.itemList =res.data.data;
						  console.log(this.itemList)
                }
            });

        }

	  }
	}
</script>
<style>
</style>

界面显示

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐